Generate a random UUID/GUID

yourbasic.org/golang

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:])
fmt.Println(uuid)
46c6b063-c738-7fef-bc95-b31a13ca7989

Limitations

This UUID doesn’t conform to RFC 4122. In particular, it doesn’t contain any version or variant numbers.

Warning: The rand.Read call returns an error if the underlying system call fails. For instance if it can't read /dev/urandom on a Unix system, or if CryptAcquireContext fails on a Windows system.

Share this page: