Code guide

Generate UUIDs in Go

Generate UUIDs in Go with the google/uuid package, including UUID v4, UUID v7, parsing and validation.

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.

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, _ := uuid.NewV7()       // time-ordered UUID v7 (google/uuid v1.6+)
    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 {
    // reject invalid UUID
}
_ = id

FAQ

Generate UUIDs in Go questions

Does Go have a built-in UUID type?

No. The standard library has no UUID type, so most Go projects use the google/uuid package for generation, parsing and formatting.

Can Go generate UUID v7?

Yes. google/uuid v1.6 and later provide uuid.NewV7() for time-ordered identifiers.

Should I store Go UUIDs as text or bytes?

Use your database native UUID type where available. google/uuid can marshal to both text and 16-byte forms.

Generate UUID in Go - google/uuid Examples