The uuid Package in Go 1.27's Standard Library: When to Use New() vs. NewV7()Note · digest for November 23
Infographic patent blueprint of the uuid identifier structure in Go's standard library
Note3 sections≈ 4 min

The uuid Package in Go 1.27's Standard Library: When to Use New() vs. NewV7()

You start a new Go service, reach primary keys, and hit the usual fork in the road. Auto-incrementing int64 works fine until you need client-side IDs, shard merging, or hidden row counts. So you pick UUID—and immediately pull github.com/google/uuid into go.mod.

In Go 1.27, you no longer need that dependency for everyday tasks. The standard library now includes a built-in uuid package following RFC 9562 (proposal #62026). Importing it is as short as "uuid".

New() vs. NewV7(): randomness or database order

Under the hood, uuid.UUID is a plain fixed array: type UUID [16]byte. No hidden pointers: values compare directly with == and work as keys in map[uuid.UUID]T without extra allocations.

The package provides three CSPRNG-backed generators. One nice upgrade over google/uuid: none of them return an error—you get a UUID straight away. uuid.New() is the default when the exact version doesn't matter (currently equivalent to uuid.NewV4()). NewV4() packs 122 random bits, making it great for tokens and request IDs.

uuid.NewV7(), on the other hand, puts a Unix timestamp in milliseconds into the top 48 bits and fills at least 62 bits with randomness. Why does your database care? In a standard B-tree index, random UUIDv4 values scatter new rows across pages and fragment the tree. With NewV7(), the key prefix grows over time, so new rows append cleanly to the end of the index.

RFC 9562 boundary values are exposed as functions rather than global variables: uuid.Nil() (Section 5.9, all zeros) and uuid.Max() (Section 5.10, all fs). Note one detail: uuid.Nil() is not Go's nil, so check empty keys with id == uuid.Nil(), while uuid.Max() helps in range checks like Nil <= UUIDv7 <= Max.

Parsing, comparison, and JSON without boilerplate

In real services, IDs constantly travel between HTTP, JSON, and databases. Here is how basic operations look in the standard package.

package main

import (
    "fmt"
    "log"
    "uuid"
)

func main() {
    // Random ID when creation order does not matter
    reqID := uuid.New()

    // Time-sorted key for database inserts
    orderID := uuid.NewV7()

    // Parse supports 4 string formats and any hex case
    parsed, err := uuid.Parse(orderID.String())
    if err != nil {
        log.Fatal(err)
    }

    // Direct comparison via ==, just like any [16]byte
    fmt.Println(orderID == parsed, reqID != uuid.Nil())
}

Parse and the panicking MustParse accept four string formats: canonical hyphenated (f81d4fae-7dec-11d0-a765-00a0c91e6bf6), braced ({...}), URN (urn:uuid:...), and 32 unhyphenated hex characters in any case. String() always outputs lowercase canonical form with hyphens.

For sorting, the Compare method compares bytes in big-endian order (most significant byte first, RFC 9562 Section 6.11), so newer UUIDv7 values always sort after older ones.

package main

import (
    "encoding/json"
    "fmt"
    "slices"
    "uuid"
)

type Order struct {
    // MarshalText and UnmarshalText are picked up by encoding/json
    ID uuid.UUID `json:"id"`
}

func main() {
    ids := []uuid.UUID{uuid.NewV7(), uuid.NewV7()}

    // Sort slice per RFC 9562 (big-endian) with no wrapper needed
    slices.SortFunc(ids, uuid.UUID.Compare)

    raw, _ := json.Marshal(Order{ID: ids[0]})
    fmt.Println(string(raw))
}

UUID implements encoding.TextMarshaler, encoding.TextUnmarshaler, and encoding.TextAppender. That means encoding/json serializes and parses it automatically without custom code, and AppendText lets you append IDs straight into an existing buffer with zero extra allocations.

Where NewV7() magic ends and when google/uuid still wins

It is easy to fall into a trap with NewV7(): you read "time-sorted" and assume strict global event ordering across your whole cluster. That won't happen. Monotonicity is only guaranteed on a single machine, and only while the system clock doesn't step backward. An NTP adjustment or clock skew between two servers can easily flip record order.

The go1.27.3 release also leaves out a few APIs. The standard library omits deterministic UUIDv3/UUIDv5 (namespace + name) and legacy UUIDv1/UUIDv6. Furthermore, UUID lacks Scan and Value (database/sql.Scanner and driver.Valuer). If you migrate from google/uuid in raw database/sql code, you will need to pass id.String(), use a driver like pgx, or write a thin wrapper. And for libraries supporting Go older than 1.27, github.com/google/uuid remains necessary.

Want a deep diveVotes help us choose what to break down in detail. This material has 0 votes.
Sources · 3