UUIDs
suggest changeA UUID (Universally Unique Identifier) is a 128-bit value used as an id that can be generated anywhere, without coordination, and is still unique in practice. It's usually written as 32 hex digits in 5 groups: 01a14bc7-9c25-730b-a167-c148d8f18a92.
For years Go programs used a third-party package, most often github.com/google/uuid. Go 1.27 added the uuid package to the standard library. Its import path is just uuid:
import "uuid"
The package is small:
uuid.UUIDis a[16]bytearrayNew,NewV4,NewV7generate new UUIDsParse,MustParseconvert a string to aUUIDNil,Maxreturn the all-zeros and all-ones UUIDs- methods:
String,Compare,MarshalText,AppendText,UnmarshalText
It implements the two versions recommended by RFC 9562: version 4 (random) and version 7 (time-ordered).
Generating UUIDs
package main
import (
"fmt"
"uuid"
)
func main() {
a := uuid.New()
b := uuid.NewV4()
c := uuid.NewV7()
fmt.Println(a)
fmt.Println(b)
fmt.Println(c)
// a UUID is a [16]byte array
fmt.Println(len(c), c[0], c[15])
// version is the high nibble of byte 6
fmt.Println("versions:", a[6]>>4, b[6]>>4, c[6]>>4)
fmt.Printf("%v\n", c)
fmt.Printf("%s\n", c)
fmt.Printf("%q\n", c)
fmt.Printf("%x\n", c[:])
}
322d850b-b161-404b-b106-176931262109
704f997e-2dc4-4156-8c0c-4ff29b7bd4dd
01a14bc7-9c25-730b-a167-c148d8f18a92
16 1 146
versions: 4 4 7
01a14bc7-9c25-730b-a167-c148d8f18a92
01a14bc7-9c25-730b-a167-c148d8f18a92
"01a14bc7-9c25-730b-a167-c148d8f18a92"
01a14bc79c25730ba167c148d8f18a92
NewV4()returns a version 4 UUID: 122 random bits plus 6 bits that encode the version and variant.NewV7()returns a version 7 UUID: a 48-bit Unix timestamp in milliseconds, followed by random bits. Note how it starts with01a14bc7-9c25: that's the current time. All UUIDs generated in the same period share this prefix.New()is the "I don't care" choice. Today it's the same asNewV4(), but the documentation reserves the right to change it. If you rely on a specific version (for example, you want ids sorted by time), callNewV4orNewV7explicitly.UUIDhas aStringmethod, sofmtprints it in the standard lowercase hex-and-dash form. Use%xon a sliceu[:]to get the 32 hex digits without dashes.
The random bits come from crypto/rand, the same source as for cryptographic keys (see Random numbers). There's no error to check: the functions never fail.
There's no Version() method. If you need it, read the high 4 bits of byte 6, as above.
Parsing
Parse accepts the standard form and a few common variations. Hex digits can be upper or lower case:
package main
import (
"fmt"
"uuid"
)
func main() {
inputs := []string{
"f81d4fae-7dec-11d0-a765-00a0c91e6bf6",
"F81D4FAE-7DEC-11D0-A765-00A0C91E6BF6",
"{f81d4fae-7dec-11d0-a765-00a0c91e6bf6}",
"urn:uuid:f81d4fae-7dec-11d0-a765-00a0c91e6bf6",
"f81d4fae7dec11d0a76500a0c91e6bf6",
"f81d4fae-7dec-11d0-a765-00a0c91e6bf", // too short
"f81d4fae_7dec_11d0_a765_00a0c91e6bf6", // wrong separator
"g81d4fae-7dec-11d0-a765-00a0c91e6bf6", // not hex
}
for _, s := range inputs {
u, err := uuid.Parse(s)
if err != nil {
fmt.Printf("%-46s error: %v\n", s, err)
continue
}
fmt.Printf("%-46s %s\n", s, u)
}
// MustParse panics on error: use it for constants
ns := uuid.MustParse("6ba7b810-9dad-11d1-80b4-00c04fd430c8")
fmt.Println(ns)
}
f81d4fae-7dec-11d0-a765-00a0c91e6bf6 f81d4fae-7dec-11d0-a765-00a0c91e6bf6
F81D4FAE-7DEC-11D0-A765-00A0C91E6BF6 f81d4fae-7dec-11d0-a765-00a0c91e6bf6
{f81d4fae-7dec-11d0-a765-00a0c91e6bf6} f81d4fae-7dec-11d0-a765-00a0c91e6bf6
urn:uuid:f81d4fae-7dec-11d0-a765-00a0c91e6bf6 f81d4fae-7dec-11d0-a765-00a0c91e6bf6
f81d4fae7dec11d0a76500a0c91e6bf6 f81d4fae-7dec-11d0-a765-00a0c91e6bf6
f81d4fae-7dec-11d0-a765-00a0c91e6bf error: invalid uuid
f81d4fae_7dec_11d0_a765_00a0c91e6bf6 error: invalid uuid
g81d4fae-7dec-11d0-a765-00a0c91e6bf6 error: invalid uuid
6ba7b810-9dad-11d1-80b4-00c04fd430c8
- The 4 accepted forms are: standard, in braces (common on Windows), as a URN and 32 hex digits without dashes.
String()always produces the canonical lowercase form, so parse-then-print normalizes input.- The error is always the same
invalid uuid. It doesn't say what's wrong, so wrap it with the input if you report it to a user. Parseonly checks the syntax. Any 128-bit value is accepted, including versions the package can't generate (the example is a version 1 UUID). If your API only accepts ids you generated, check the version byte yourself.MustParseis meant for package-level constants and tests, where an invalid string is a bug. Don't use it on user input.
Nil and Max UUIDs
The Nil UUID is all zeros; the Max UUID is all ones. They're used as "no value" and "upper bound" markers:
package main
import (
"fmt"
"uuid"
)
type Order struct {
ID uuid.UUID
ParentID uuid.UUID // zero value means "no parent"
}
func main() {
fmt.Println(uuid.Nil())
fmt.Println(uuid.Max())
var o Order
fmt.Println(o.ID == uuid.Nil())
fmt.Println(o.ID == uuid.UUID{})
o.ID = uuid.NewV7()
if o.ParentID == uuid.Nil() {
fmt.Println("order has no parent")
}
fmt.Println(o.ID != uuid.Nil())
}
00000000-0000-0000-0000-000000000000
ffffffff-ffff-ffff-ffff-ffffffffffff
true
true
order has no parent
true
Nil and Max are functions, not variables, so no code can accidentally change them (in github.com/google/uuid they are variables).
The Nil UUID is the zero value of uuid.UUID, and it's not the same as Go's nil. A uuid.UUID can't be nil because it's an array. If you need to tell "missing" from "all zeros", use *uuid.UUID, but usually checking == uuid.Nil() is enough, since generated UUIDs are never all zeros.
Comparing, sorting and map keys
UUID is an array, so == works and it can be a map key. Compare returns -1, 0 or +1 and orders UUIDs byte by byte, which is the order RFC 9562 defines (and the order PostgreSQL uses for its uuid type).
The method expression uuid.UUID.Compare has the signature func(a, b uuid.UUID) int, exactly what slices.SortFunc wants:
package main
import (
"fmt"
"slices"
"uuid"
)
func main() {
// v7 UUIDs generated in sequence are already sorted
var ids []uuid.UUID
for range 5 {
ids = append(ids, uuid.NewV7())
}
fmt.Println(slices.IsSortedFunc(ids, uuid.UUID.Compare))
// v4 UUIDs are in random order
var rnd []uuid.UUID
for range 5 {
rnd = append(rnd, uuid.NewV4())
}
fmt.Println(slices.IsSortedFunc(rnd, uuid.UUID.Compare))
slices.SortFunc(rnd, uuid.UUID.Compare)
for _, u := range rnd {
fmt.Println(u)
}
a := uuid.MustParse("00000000-0000-0000-0000-000000000001")
b := uuid.MustParse("00000000-0000-0000-0000-000000000002")
fmt.Println(a.Compare(b), b.Compare(a), a.Compare(a))
fmt.Println(uuid.Nil().Compare(a), uuid.Max().Compare(a))
}
true
false
755f4710-5db1-4c79-8d57-f48046d9a62e
790f3512-5036-4d1f-b8b6-1fc72f27154a
9cf80823-8c6e-4144-ad54-b57bf3af084b
a46d98d3-055f-4ae3-898c-ada1b0c59bee
cfa474f4-98a5-48d1-ac90-888156b2b2d7
-1 1 0
-1 1
Sorting by Compare gives the same order as sorting the String() forms, because the hex digits are lowercase and fixed width.
Using UUIDs as map keys:
package main
import (
"fmt"
"uuid"
)
type User struct {
ID uuid.UUID
Name string
}
func main() {
alice := User{ID: uuid.NewV7(), Name: "alice"}
bob := User{ID: uuid.NewV7(), Name: "bob"}
// UUID is comparable, so it works as a map key
byID := map[uuid.UUID]User{
alice.ID: alice,
bob.ID: bob,
}
// round-trip through a string, e.g. from a URL path
s := bob.ID.String()
id, err := uuid.Parse(s)
if err != nil {
panic(err)
}
fmt.Println(byID[id].Name)
_, ok := byID[uuid.NewV7()]
fmt.Println(ok)
}
bob
false
A map[uuid.UUID]T is better than map[string]T with UUID strings: the key is 16 bytes instead of a 36-byte string, and "ABC..." vs "abc..." can't create two entries for the same id.
Version 7: ordered by time
A version 7 UUID puts the creation time in the most significant bits:
01a14bc7-9c25 - 7 30b - a167-c148d8f18a92
|___________| | |__| |________________|
48-bit Unix ms | 12 bits variant + 62 random bits
version
Go's implementation fills the 12 bits after the version with a sub-millisecond fraction of the time (1/4096 of a millisecond). If two calls get the same timestamp, the second one uses the previous timestamp plus one. As a result, NewV7 always returns increasing UUIDs within a process, even when called from many goroutines at once. The only exception is when the system clock moves backwards.
You can see it in UUIDs generated in a tight loop: the timestamp part is the same and the next 4 hex digits count up: ...-7d5e-..., ...-7d5f-..., ...-7d60-....
The package doesn't have a function to get the time back, but it's easy to write:
package main
import (
"encoding/binary"
"fmt"
"time"
"uuid"
)
// v7Time returns the creation time stored in a version 7 UUID.
func v7Time(u uuid.UUID) (time.Time, bool) {
if u[6]>>4 != 7 {
return time.Time{}, false
}
// the first 48 bits are milliseconds since the Unix epoch
var b [8]byte
copy(b[2:], u[:6])
ms := binary.BigEndian.Uint64(b[:])
return time.UnixMilli(int64(ms)), true
}
func main() {
u := uuid.NewV7()
t, ok := v7Time(u)
fmt.Println(u)
fmt.Println(t.UTC().Format(time.RFC3339Nano), ok)
_, ok = v7Time(uuid.NewV4())
fmt.Println(ok)
}
01a14bc8-2788-7a6c-a851-71c0cc17bf1e
2026-10-17T21:32:50.952Z true
false
Because the time is in the id, anyone who sees a v7 UUID knows when it was created. That's usually fine, but if the creation time of a record is sensitive, use v4.
Why v7 is better for database keys
Most databases store a primary key in a B-tree index, which keeps keys sorted.
With random v4 keys, every insert goes to a random place in the index. The database has to read and modify pages all over the index, and pages split when a new key lands in the middle of a full page. Over time pages end up partially empty, the index is bigger, and once it no longer fits in memory every insert needs a disk read.
v7 keys are almost always larger than all existing keys, so inserts go to the end of the index, the same as with an auto-increment integer. Recently inserted rows are also close together, which helps queries that read recent data.
Here's an example that inserts 500,000 rows into PostgreSQL with each kind of key, using pgx CopyFrom, and reports the size of the primary key index:
package main
import (
"context"
"fmt"
"log"
"os"
"time"
"uuid"
"github.com/jackc/pgx/v5"
)
func load(ctx context.Context, conn *pgx.Conn, table string, gen func() uuid.UUID) {
_, err := conn.Exec(ctx, fmt.Sprintf(`CREATE TABLE %s (id uuid PRIMARY KEY, n int)`, table))
if err != nil {
log.Fatal(err)
}
const total, batch = 500_000, 1000
start := time.Now()
for i := 0; i < total; i += batch {
rows := make([][]any, batch)
for j := range rows {
rows[j] = []any{gen(), i + j}
}
_, err := conn.CopyFrom(ctx, pgx.Identifier{table}, []string{"id", "n"}, pgx.CopyFromRows(rows))
if err != nil {
log.Fatal(err)
}
}
elapsed := time.Since(start)
var size string
conn.QueryRow(ctx, fmt.Sprintf(`SELECT pg_size_pretty(pg_relation_size('%s_pkey'))`, table)).Scan(&size)
fmt.Printf("%s: %v, primary key index %s\n", table, elapsed.Round(10*time.Millisecond), size)
}
func main() {
ctx := context.Background()
conn, err := pgx.Connect(ctx, os.Getenv("DATABASE_URL"))
if err != nil {
log.Fatal(err)
}
defer conn.Close(ctx)
conn.Exec(ctx, `DROP TABLE IF EXISTS ids_v4, ids_v7`)
load(ctx, conn, "ids_v4", uuid.NewV4)
load(ctx, conn, "ids_v7", uuid.NewV7)
}
ids_v4: 1.78s, primary key index 19 MB
ids_v7: 1.73s, primary key index 15 MB
The v4 index is about 25% larger for the same data, because of the half-empty pages left by splits. At this size everything fits in memory, so the times are close. The gap grows a lot when the index is bigger than RAM.
Rules of thumb:
- use
NewV7for database primary keys and anything you want to sort by creation time - use
NewV4when the id shouldn't reveal when it was created - don't use either as a secret (session token, password reset link). A UUID is an identifier, not a password. Use
crypto/rand.Text()for that (see Random numbers)
JSON and text encoding
UUID implements encoding.TextMarshaler and encoding.TextUnmarshaler. Every package that understands those interfaces handles UUIDs as strings, with no extra code: encoding/json, encoding/xml, flag.TextVar, log/slog, and others.
package main
import (
"encoding/json"
"fmt"
"uuid"
)
type Event struct {
ID uuid.UUID `json:"id"`
UserID uuid.UUID `json:"user_id"`
ParentID *uuid.UUID `json:"parent_id,omitempty"`
Tags map[uuid.UUID]string `json:"tags,omitempty"`
}
func main() {
e := Event{
ID: uuid.MustParse("01a14bc7-9c25-730b-a167-c148d8f18a92"),
UserID: uuid.MustParse("322d850b-b161-404b-b106-176931262109"),
Tags: map[uuid.UUID]string{
uuid.MustParse("704f997e-2dc4-4156-8c0c-4ff29b7bd4dd"): "important",
},
}
d, err := json.MarshalIndent(e, "", " ")
if err != nil {
panic(err)
}
fmt.Println(string(d))
in := `{"id":"{01A14BC7-9C25-730B-A167-C148D8F18A92}","user_id":"322d850bb161404bb106176931262109"}`
var e2 Event
if err := json.Unmarshal([]byte(in), &e2); err != nil {
panic(err)
}
fmt.Println(e2.ID, e2.UserID, e2.ParentID)
bad := `{"id":"not-a-uuid"}`
err = json.Unmarshal([]byte(bad), &e2)
fmt.Println(err)
}
{
"id": "01a14bc7-9c25-730b-a167-c148d8f18a92",
"user_id": "322d850b-b161-404b-b106-176931262109",
"tags": {
"704f997e-2dc4-4156-8c0c-4ff29b7bd4dd": "important"
}
}
01a14bc7-9c25-730b-a167-c148d8f18a92 322d850b-b161-404b-b106-176931262109 <nil>
invalid uuid
- without
MarshalText,encoding/jsonwould encode a[16]byteas an array of 16 numbers. With it, you get a string. - UUIDs also work as map keys in JSON objects, because map keys that implement
TextMarshalerare encoded with it. - decoding accepts every form
Parseaccepts and always re-encodes in canonical form.
An optional UUID doesn't have to be a pointer. Since Go 1.24 omitzero omits a field that has its zero value, which for uuid.UUID is the Nil UUID. (omitempty doesn't work here: it never omits arrays of non-zero length.)
package main
import (
"encoding/json"
"fmt"
"uuid"
)
type Comment struct {
ID uuid.UUID `json:"id"`
ParentID uuid.UUID `json:"parent_id,omitzero"`
Text string `json:"text"`
}
func main() {
top := Comment{ID: uuid.MustParse("01a14bc7-9c25-730b-a167-c148d8f18a92"), Text: "hello"}
reply := Comment{
ID: uuid.MustParse("01a14bc7-9c26-7aa0-8f3e-2b1d6f1c0c11"),
ParentID: top.ID,
Text: "hi",
}
for _, c := range []Comment{top, reply} {
d, _ := json.Marshal(c)
fmt.Println(string(d))
}
}
{"id":"01a14bc7-9c25-730b-a167-c148d8f18a92","text":"hello"}
{"id":"01a14bc7-9c26-7aa0-8f3e-2b1d6f1c0c11","parent_id":"01a14bc7-9c25-730b-a167-c148d8f18a92","text":"hi"}
If you need a different format (for example, base64 of the 16 bytes to save space), wrap uuid.UUID in your own type and implement MarshalJSON, as shown in Custom JSON marshaling.
AppendText
AppendText implements encoding.TextAppender (Go 1.24). It appends the string form to a byte slice, which avoids allocating a string for each UUID when you build output in a buffer:
package main
import (
"fmt"
"uuid"
)
func main() {
ids := []uuid.UUID{
uuid.MustParse("01a14bc7-9c25-730b-a167-c148d8f18a92"),
uuid.MustParse("01a14bc7-9c26-7aa0-8f3e-2b1d6f1c0c11"),
}
// build "id1,id2" into one buffer without a string per UUID
buf := make([]byte, 0, 64)
for i, id := range ids {
if i > 0 {
buf = append(buf, ',')
}
buf, _ = id.AppendText(buf) // the error is always nil
}
fmt.Println(string(buf))
b, err := ids[0].MarshalText()
fmt.Println(string(b), len(b), err)
var u uuid.UUID
err = u.UnmarshalText([]byte("urn:uuid:01a14bc7-9c25-730b-a167-c148d8f18a92"))
fmt.Println(u, err)
}
01a14bc7-9c25-730b-a167-c148d8f18a92,01a14bc7-9c26-7aa0-8f3e-2b1d6f1c0c11
01a14bc7-9c25-730b-a167-c148d8f18a92 36 <nil>
01a14bc7-9c25-730b-a167-c148d8f18a92 <nil>
There's no MarshalBinary. The binary form is the array itself: use u[:] to get the 16 bytes and copy(u[:], b) to go back.
Storing UUIDs in a database
In Go 1.27 database/sql knows about uuid.UUID:
- a
uuid.UUIDpassed as a query argument is sent as its string form Scaninto a*uuid.UUIDaccepts a string, a 16-byte[]byte(raw bytes) or a 36-byte[]byte(text)
That covers drivers that don't know anything about UUIDs. See SQL for the general database/sql API.
SQLite
SQLite has no UUID type. Store them as TEXT (readable, 36 bytes) or BLOB (16 bytes, pass u[:] as the argument). With TEXT you can pass a uuid.UUID directly. The example uses modernc.org/sqlite (see SQLite):
package main
import (
"database/sql"
"fmt"
"log"
"uuid"
_ "modernc.org/sqlite"
)
type Note struct {
ID uuid.UUID
Text string
}
func main() {
db, err := sql.Open("sqlite", ":memory:")
if err != nil {
log.Fatal(err)
}
defer db.Close()
_, err = db.Exec(`CREATE TABLE notes (
id TEXT PRIMARY KEY,
text TEXT NOT NULL
)`)
if err != nil {
log.Fatal(err)
}
for _, text := range []string{"first", "second", "third"} {
// a uuid.UUID argument is sent as its string form
_, err := db.Exec(`INSERT INTO notes (id, text) VALUES (?, ?)`, uuid.NewV7(), text)
if err != nil {
log.Fatal(err)
}
}
// v7 ids sort by creation time, so ORDER BY id is insertion order
rows, err := db.Query(`SELECT id, text FROM notes ORDER BY id`)
if err != nil {
log.Fatal(err)
}
defer rows.Close()
var notes []Note
for rows.Next() {
var n Note
// Scan parses the text column into a uuid.UUID
if err := rows.Scan(&n.ID, &n.Text); err != nil {
log.Fatal(err)
}
notes = append(notes, n)
}
if err := rows.Err(); err != nil {
log.Fatal(err)
}
for _, n := range notes {
fmt.Println(n.ID, n.Text)
}
var text string
err = db.QueryRow(`SELECT text FROM notes WHERE id = ?`, notes[1].ID).Scan(&text)
fmt.Println(text, err)
}
01a14bca-2fee-7d5e-8da5-e39e2542ea0e first
01a14bca-2fee-7d5f-baab-fd07a9154503 second
01a14bca-2fee-7d60-84ca-b8ae6b632c0b third
second <nil>
If you mix TEXT and BLOB storage, lookups won't match: '01a1...' and X'01a1...' are different values to SQLite. Pick one format per column. Since String() is always lowercase, text ids compare correctly as long as all of them were written by Go (or normalized to lowercase).
PostgreSQL
PostgreSQL has a native 16-byte uuid type. With pgx, uuid.UUID works for both arguments and Scan, because pgx encodes any [16]byte type as uuid:
package main
import (
"context"
"fmt"
"log"
"os"
"uuid"
"github.com/jackc/pgx/v5/pgxpool"
)
type User struct {
ID uuid.UUID
Email string
}
func main() {
ctx := context.Background()
pool, err := pgxpool.New(ctx, os.Getenv("DATABASE_URL"))
if err != nil {
log.Fatal(err)
}
defer pool.Close()
_, err = pool.Exec(ctx, `
CREATE TEMP TABLE users (
id uuid PRIMARY KEY,
email text NOT NULL UNIQUE
)`)
if err != nil {
log.Fatal(err)
}
id := uuid.NewV7()
_, err = pool.Exec(ctx, `INSERT INTO users (id, email) VALUES ($1, $2)`,
id, "alice@example.com")
if err != nil {
log.Fatal(err)
}
var u User
err = pool.QueryRow(ctx, `SELECT id, email FROM users WHERE id = $1`, id).
Scan(&u.ID, &u.Email)
if err != nil {
log.Fatal(err)
}
fmt.Println(u.ID == id, u.Email)
var s string
err = pool.QueryRow(ctx, `SELECT id::text FROM users`).Scan(&s)
fmt.Println(s == id.String(), err)
}
true alice@example.com
true <nil>
Generate the ids in Go rather than with a column default like DEFAULT gen_random_uuid(): you know the id before the insert (no need for RETURNING id), you can use it to link rows inserted in the same transaction, and you control the version. gen_random_uuid() creates v4 UUIDs. PostgreSQL 18 added uuidv7() if you do want the database to generate them.
Use the uuid column type, not text: it takes 16 bytes instead of 37 and compares faster.
Migrating from github.com/google/uuid
The standard package was modeled on github.com/google/uuid, and both define UUID as [16]byte, so most code changes are mechanical:
| github.com/google/uuid | uuid (Go 1.27) |
|---|---|
uuid.New() |
uuid.New() |
uuid.NewRandom() (returns error) |
uuid.NewV4() |
uuid.NewV7() (returns error) |
uuid.NewV7() |
uuid.NewString() |
uuid.New().String() |
uuid.Parse, uuid.MustParse |
same |
uuid.Nil, uuid.Max (variables) |
uuid.Nil(), uuid.Max() |
u.Version(), u.Variant() |
u[6]>>4, u[8]>>6 |
u.Time() |
decode it yourself (see above) |
u.Value(), u.Scan() |
built into database/sql |
uuid.NullUUID |
*uuid.UUID or sql.Null[uuid.UUID] |
MarshalBinary, UnmarshalBinary |
u[:], copy(u[:], b) |
NewUUID (v1), NewMD5 (v3), NewSHA1 (v5), NewV6 |
not available |
uuid.ParseBytes, uuid.FromBytes |
UnmarshalText, copy |
In a large code base you can migrate one package at a time. A plain type conversion moves a value between the two types:
package main
import (
"fmt"
"uuid"
guuid "github.com/google/uuid"
)
func main() {
// both types are [16]byte, so a plain conversion works
g := guuid.MustParse("01a14bc7-9c25-730b-a167-c148d8f18a92")
s := uuid.UUID(g)
back := guuid.UUID(s)
fmt.Println(s, back == g)
// things the standard package doesn't have
fmt.Println(g.Version(), g.Variant())
sec, nsec := g.Time().UnixTime()
fmt.Println(sec, nsec)
v5 := guuid.NewSHA1(guuid.NameSpaceDNS, []byte("example.com"))
fmt.Println(v5, v5.Version())
}
01a14bc7-9c25-730b-a167-c148d8f18a92 true
VERSION_7 RFC4122
1792272735 269000000
cfbff0d1-9375-5685-968c-48ce8b15ae17 VERSION_5
Both packages are named uuid, so give one of them a different name when you import both.
If you need name-based UUIDs (v3, v5, which always produce the same UUID for the same name) or the legacy v1/v6, keep using github.com/google/uuid for those.
UUIDs stored in a database or JSON don't change: both packages use the same text format and the same 16 bytes.
Summary
import "uuid"(Go 1.27).uuid.UUIDis a comparable[16]byte.NewV7()for database keys and time-sorted ids,NewV4()for ids that shouldn't reveal their creation time,New()when you don't care.Parseaccepts standard, braced, URN and dash-less forms;Stringalways returns lowercase with dashes.Nil()is the zero value. Useomitzeroto omit it in JSON.slices.SortFunc(ids, uuid.UUID.Compare)sorts UUIDs.- JSON, XML,
flag.TextVaranddatabase/sqlhandleuuid.UUIDwith no extra code. - UUIDs are identifiers, not secrets.