Home >Backend Development >Golang >How to Generate UUIDs in Go: The Best Approach?
Generating UUIDs with Go Language
The code snippet you provided sets the values of u[8] and u[6] to ensure that the result is a valid UUID:
u[8] = (u[8] | 0x80) & 0xBF // ensures the value is within the valid range for version 4 UUIDs u[6] = (u[6] | 0x40) & 0x4F // ensures the value is within the valid range for version 4 UUIDs
However, this is not the recommended method of generating UUIDs in Go.
Using the Official UUID Package
Google released an official UUID package for Go: https://github.com/google/uuid. This package simplifies the process of generating UUIDs:
package main import ( "fmt" "github.com/google/uuid" ) func main() { id := uuid.New() fmt.Println(id.String()) }
This code generates a random version 4 UUID and prints it as a string. You can try it out here: https://play.golang.org/p/6YPi1djUMj9.
The above is the detailed content of How to Generate UUIDs in Go: The Best Approach?. For more information, please follow other related articles on the PHP Chinese website!