Is there a method to generate a UUID with go language

后端 未结 12 1717
温柔的废话
温柔的废话 2020-12-07 12:15

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 thi         


        
12条回答
  •  既然无缘
    2020-12-07 12:30

    You can generate UUIDs using the go-uuid library. This can be installed with:

    go get github.com/nu7hatch/gouuid
    

    You can generate random (version 4) UUIDs with:

    import "github.com/nu7hatch/gouuid"
    
    ...
    
    u, err := uuid.NewV4()
    

    The returned UUID type is a 16 byte array, so you can retrieve the binary value easily. It also provides the standard hex string representation via its String() method.

    The code you have also looks like it will also generate a valid version 4 UUID: the bitwise manipulation you perform at the end set the version and variant fields of the UUID to correctly identify it as version 4. This is done to distinguish random UUIDs from ones generated via other algorithms (e.g. version 1 UUIDs based on your MAC address and time).

提交回复
热议问题