Generate a UUID in Go

How to generate a UUID in Go with github.com/google/uuid: New for v4, NewV7 for time ordered, NewSHA1 for name based, Parse and Validate, plus a dependency free v4 with crypto/rand.

Try it here

Generate a UUID to paste into your Go code, in any version and format.

Format

Your UUIDs

Copy one, copy them all, or download the list. The format options above apply to everything shown here.

    The standard choice: google/uuid

    go get github.com/google/uuid
    
    import "github.com/google/uuid"
    
    id := uuid.New()              // v4, panics only if the OS random source fails
    id7, err := uuid.NewV7()      // v7, time ordered
    id1, err := uuid.NewUUID()    // v1
    id5 := uuid.NewSHA1(uuid.NameSpaceDNS, []byte("example.com"))  // v5
    id3 := uuid.NewMD5(uuid.NameSpaceDNS, []byte("example.com"))   // v3
    
    id.String()   // "f47ac10b-58cc-4372-a567-0e02b2c3d479"
    id[:]         // the 16 bytes, uuid.UUID is a [16]byte

    uuid.New() is a wrapper around NewRandom() that panics on error, which is fine because crypto/rand failing means the machine has bigger problems. Use v7 for database keys, see why.

    Parse and validate

    u, err := uuid.Parse("f47ac10b-58cc-4372-a567-0e02b2c3d479")
    if err != nil {
        // not a uuid
    }
    u.Version()   // 4
    u.Variant()   // RFC4122
    
    err = uuid.Validate(s)   // just the check, no value
    u = uuid.MustParse(s)    // panics on bad input, for constants

    Parse accepts the plain form, braces, the urn:uuid: prefix and 32 hex characters. If your API should only accept the canonical 36 character form, check len(s) == 36 first.

    Without a dependency

    import (
        "crypto/rand"
        "fmt"
    )
    
    func newV4() (string, error) {
        var b [16]byte
        if _, err := rand.Read(b[:]); err != nil {
            return "", err
        }
        b[6] = (b[6] & 0x0f) | 0x40   // version 4
        b[8] = (b[8] & 0x3f) | 0x80   // variant RFC
        return fmt.Sprintf("%x-%x-%x-%x-%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:]), nil
    }

    This is exactly what the library does. Reach for it only when adding a module is not an option.

    Databases

    // database/sql with pgx: uuid.UUID implements Scanner and Valuer
    var id uuid.UUID
    err := db.QueryRow("SELECT id FROM orders WHERE ...").Scan(&id)
    
    // GORM
    type Order struct {
        ID uuid.UUID `gorm:"type:uuid;primaryKey"`
    }

    Mistakes to avoid

    • math/rand for ids. Never. It is deterministic and predictable. Use the library or crypto/rand.
    • Comparing with == on strings from different sources. One may be uppercase. Parse both and compare the uuid.UUID values.
    • MustParse on user input. It panics. Use Parse and handle the error.

    Frequently asked questions

    Which Go UUID package should I use?

    github.com/google/uuid. It is maintained by Google, has v1 to v7, and is what most database drivers and frameworks expect. github.com/gofrs/uuid is a fine alternative with the same features.

    How do I generate a UUID v7 in Go?

    uuid.NewV7() from google/uuid, available since v1.4.0. It returns an error only if the random source fails.

    Does uuid.New() ever return duplicates?

    Not in practice. It draws 122 random bits from crypto/rand. See our post on collision probability for the numbers.

    ↑ Top
    Copied!