Rust UUIDs for IDs
A UUID is a 128-bit id drawn mostly at random. Every machine can mint its own UUID without asking anyone.
Mint a fresh id
new_v4 draws the bits at random. Run it twice and the two ids differ.
let id = Uuid::new_v4();
println!("id = {id}");Read one back
parse_str rebuilds an id from its text. The text form is the one you meet in URLs and databases.
let id = Uuid::parse_str("550e8400-e29b-41d4-a716-446655440000").unwrap();
println!("hyphenated = {}", id.hyphenated());The compact form
simple drops the hyphens. Thirty-two hex characters remain.
println!("simple = {}", id.simple());Ask what kind it is
A few bits inside the id record its version and variant. This one is a random version 4 id.
println!("version 4 = {}", id.get_version() == Some(Version::Random));Two famous constants
nil is all zero bits. max is all one bits. Both print like any other id.
println!("nil = {}", Uuid::nil());
println!("max = {}", Uuid::max());Example
// Cargo.toml: uuid = { version = "1", features = ["v4"] }
use uuid::{Uuid, Variant, Version};
fn main() {
let id = Uuid::parse_str("550e8400-e29b-41d4-a716-446655440000").unwrap();
println!("hyphenated = {}", id.hyphenated());
println!("simple = {}", id.simple());
println!("version 4 = {}", id.get_version() == Some(Version::Random));
println!("rfc variant = {}", id.get_variant() == Variant::RFC4122);
let back = Uuid::from_u128(id.as_u128());
println!("round trip = {}", back == id);
let fresh = Uuid::new_v4();
println!("fresh is version 4 = {}", fresh.get_version() == Some(Version::Random));
}Key points
- Add uuid = { version = "1", features = ["v4"] } to Cargo.toml
- The v4 feature turns on random ids
- A UUID holds 128 bits
- The text form groups them 8-4-4-4-12 as hex
- Version 4 means the bits were drawn at random
- No clock, no counter and no machine name takes part
- Two v4 ids can collide in theory
- The odds sit below winning a lottery many times over, so systems treat them as unique
- Use as_u128 and from_u128 to store an id as one number
- The round trip is exact
- Databases, orders and uploads all need names that never collide.
- A counter works until two machines count at once.
In this example, the programme reads the most quoted UUID in the docs. It prints the hyphenated form, then the compact simple form. Two questions follow. The version check says true: this is a random version 4 id. The variant check says true too: its bits follow the RFC layout. The id then takes a trip through as_u128 and from_u128 and comes back equal. A fresh new_v4 id closes the show. It also reports version 4.
Note
An id is not a secret
A UUID names a thing in public, and anyone may see it and share it
Guard the data behind it, not the name
Try it Yourself
Edit the code, then press Run.
Running is simulated · Rust Playground
Exercise
Why can two servers mint version 4 UUIDs without asking each other?