gouuid

Is there a method to generate a UUID with Go language?


I have code that looks like this:

u := make([]byte, 16)
_, err := rand.Read(u)
if err != nil {
    return
}

u[8] = (u[8] | 0x80) & 0xBF // what does this do?
u[6] = (u[6] | 0x40) & 0x4F // what does this do?

return hex.EncodeToString(u)

It returns a string with a length of 32, but I don't think it is a valid UUID. If it is a real UUID, why is it a UUID, and what is the purpose of the code that modifies the value of u[8] and u[6]?

Is there a better way of generating UUIDs?


Solution

  • u[8] = (u[8] | 0x80) & 0xBF // what's the purpose ?
    u[6] = (u[6] | 0x40) & 0x4F // what's the purpose ?
    

    These lines clamp the values of byte 6 and 8 to a specific range. rand.Read returns random bytes in the range 0-255, which are not all valid values for a UUID. As far as I can tell, this should be done for all the values in the slice though.

    If you are on linux, you can alternatively call /usr/bin/uuidgen.

    package main
    
    import (
        "fmt"
        "log"
        "os/exec"
    )
    
    func main() {
        out, err := exec.Command("uuidgen").Output()
        if err != nil {
            log.Fatal(err)
        }
        fmt.Printf("%s", out)
    }
    

    Which yields:

    $ go run uuid.go 
    dc9076e9-2fda-4019-bd2c-900a8284b9c4