Go: Generate a random UUID (GUID)

Use the rand.Read function from package crypto/rand to generate a universally unique identifier:

b := make([]byte, 16)
_, err := rand.Read(b)
if err != nil {
        log.Fatal(err)
}
uuid := fmt.Sprintf("%x-%x-%x-%x-%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:])

Note that his UUID doesn't conform to RFC 4122. In particular, it doesn't contain any version or variant numbers.

The rand.Read call returns an error if the underlying system call fails. For instance if the runtime can't read /dev/urandom on a *nix system or if CryptAcquireContext fails on a Windows system.

Comments

Be the first to comment!