Skip to main content
Go

How to Generate UUID in Go

Using github.com/google/uuid

Go's standard library has no UUID package, which is why most projects reach for github.com/google/uuid — the de facto standard for generating a 128-bit unique identifier in any Go application. Run go get github.com/google/uuid, then call uuid.New() to produce a random, RFC 9562-compliant v4 UUID in one line, with no external service or configuration required. Below you'll find copy-paste ready code for generating a Go UUID, parsing a string back into a uuid.UUID, and the newer v7 option for time-sortable database keys. You can generate uuid python with uuid.uuid5() when you need reproducible identifiers from a namespace and name.

Generate UUID in Go

id := uuid.New()
550e8400-e29b-41d4-a716-446655440000

How to Generate a UUID in Go

Install github.com/google/uuid, the community-standard package for UUID generation in Go, then call uuid.New() to get a random v4 identifier — it's the fastest way to add unique IDs to structs, database rows, or API responses. Use the typescript uuid guide to implement type-safe UUIDs in TypeScript with strict compile-time checking.

Terminal
go get github.com/google/uuid
main.go
package main

import (
    "fmt"
    "github.com/google/uuid"
)

func main() {
    id := uuid.New()
    fmt.Println(id.String())
    // Output: 550e8400-e29b-41d4-a716-446655440000

    // Or handle the error explicitly
    id2, err := uuid.NewRandom()
    if err != nil {
        panic(err)
    }
    fmt.Println(id2)
}

Explanation

Convert a String to a UUID in Go

When a UUID arrives as a string — from a URL path, a JSON body, or a database column — parse it back into a type-safe uuid.UUID with uuid.Parse() so you can compare, store, or validate it like any other Go value. The dart uuid reference explains how to use Uuid().v4() for random UUIDs and v5() for name-based generation.

main.go
package main

import (
    "fmt"
    "log"
    "github.com/google/uuid"
)

func main() {
    id, err := uuid.Parse("550e8400-e29b-41d4-a716-446655440000")
    if err != nil {
        log.Fatal("invalid UUID:", err)
    }
    fmt.Println(id)

    // MustParse panics on invalid input - use only for
    // hardcoded constants or tests, never on user input
    fixed := uuid.MustParse("550e8400-e29b-41d4-a716-446655440000")
    fmt.Println(fixed == id)
}

Explanation

Other Options for Generating UUIDs in Go

uuid.New() covers most cases, but github.com/google/uuid v1.6+ also ships uuid.NewV7(), which generates an RFC 9562-compliant time-sortable UUID — a better fit for database primary keys than a fully random v4.

main.go
package main

import (
    "fmt"
    "github.com/google/uuid"
)

func main() {
    // Unix-timestamp-prefixed, sortable, index-friendly
    id, err := uuid.NewV7()
    if err != nil {
        panic(err)
    }
    fmt.Println(id)
}

Explanation

Comments & Feedback

Share your experience or ask questions about this tool

Copied!