Go

UUID Generation (google/uuid)

admin by @admin ADMIN
1d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
`github.com/google/uuid` is the standard UUID library. v4 (random) for IDs, v7 (time-ordered) when you want UUIDs that sort chronologically and play nicely with B-tree indexes.
Go
Raw
// go get github.com/google/uuid
package main

import (
    "fmt"

    "github.com/google/uuid"
)

func main() {
    // v4 — random (most common)
    id := uuid.New()
    fmt.Println(id)                                // f47ac10b-58cc-4372-a567-0e02b2c3d479

    // v7 — time-ordered (Go 1.6+ of the library)
    id7, _ := uuid.NewV7()
    fmt.Println(id7)                               // 01928f4d-... (chronologically sortable)

    // Parse
    parsed, err := uuid.Parse("f47ac10b-58cc-4372-a567-0e02b2c3d479")
    if err != nil { panic(err) }
    fmt.Println(parsed.Version(), parsed.Variant())

    // Bytes / String round-trip
    b, _ := id.MarshalBinary()                     // 16 raw bytes
    parsed2, _ := uuid.FromBytes(b)
    fmt.Println(parsed2 == id)                     // true
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.