Crypto Rand UUID v4 With RFC 4122 Bits

Assemble RFC 4122 version-4 UUIDs from crypto/rand bytes by setting the version and variant bits, then format canonical hex groups.

GoSecurity Boundaries

Code

snippet
package main

import (
	"crypto/rand"
	"fmt"
)

// NewUUIDv4 从 crypto/rand 取 16 字节,按 RFC 4122 设置版本与变体位
func NewUUIDv4() (string, error) {
	var b [16]byte
	if _, err := rand.Read(b[:]); err != nil {
		return "", err
	}
	b[6] = (b[6] & 0x0f) | 0x40 // version bits -> 0100
	b[8] = (b[8] & 0x3f) | 0x80 // variant bits -> 10xx
	return fmt.Sprintf("%x-%x-%x-%x-%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:16]), nil
}

func main() {
	for range 3 {
		id, err := NewUUIDv4()
		if err != nil {
			panic(err)
		}
		fmt.Println(id)
	}
}

How it works

Everything happens inside the functions NewUUIDv4 and main.

The loop for range 3 is the only repeated construct. Every fallible call checks err != nil (2 sites), so an error is handled where it happens rather than bubbling invisibly.

What to watch for

  • Runs on the standard library alone; nothing to install.
  • Error values are returned, not thrown — every call site must inspect err before using the other return values.

Using it

The callable you reach for: func NewUUIDv4() (string, error)

Running the file executes main, which drives NewUUIDv4 in order.

Key statements worth quoting

return fmt.Sprintf("%x-%x-%x-%x-%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:16]), nil
if err != nil {
	panic(err)
}
return "", err

Interactive Tools for This Topic

FAQ

How does the code signal failure?
As returned `error` values — 2 sites in the snippet check `err` before using other results.
How do you run Crypto Rand UUID v4 With RFC 4122 Bits?
The file is self-contained: run it directly, no dependencies to install beforehand.