Go has no UUID type in its standard library, so most projects use the widely trusted google/uuid package. It generates UUID v4 and, in recent versions, UUID v7, and it parses and validates strings cleanly.
Key takeaways
- Use github.com/google/uuid for generation and parsing.
- uuid.NewString() gives a random v4; NewV7() gives a time-ordered v7.
- Parse untrusted input with uuid.Parse and handle the error.
For implementation context, continue with UUID v4, UUID v7, and Rust. These pages cover the closest generator, comparison, validation or storage decisions without repeating this guide.
Generate a UUID in Go
Install the package with go get github.com/google/uuid, then generate a random v4 or a time-ordered v7. NewString returns the canonical lowercase string directly.
package main
import (
"fmt"
"github.com/google/uuid"
)
func main() {
v4 := uuid.NewString() // random UUID v4
v7, err := uuid.NewV7() // time-ordered UUID v7 (google/uuid v1.6+)
if err != nil {
panic(err) // generation can fail; do not ignore the error
}
fmt.Println(v4)
fmt.Println(v7.String())
}Parse and validate
Validate incoming identifiers by parsing them. uuid.Parse accepts hyphenated, URN and braced forms and returns an error for anything invalid, which is safer than a hand-written check.
id, err := uuid.Parse(input)
if err != nil {
return // reject invalid input before using id
}
_ = idRequire canonical UUID text at an API boundary
Parse accepts several encodings, including compact and braced values. Parsing successfully does not enforce a lowercase, hyphenated API contract. Compare the input with String() when that exact representation is required; otherwise normalize it before storing or comparing.
Check the version separately when an endpoint requires v4 or v7. A nil UUID can parse successfully but may not be a valid resource ID for your application.
func canonicalUUID(input string) (uuid.UUID, error) {
id, err := uuid.Parse(input)
if err != nil {
return uuid.Nil, err
}
if input != id.String() || id == uuid.Nil {
return uuid.Nil, fmt.Errorf("expected a non-nil canonical UUID")
}
return id, nil
}