Rust's uuid crate gives you zero-cost, type-safe UUID generation with compile-time guarantees the standard library alone doesn't provide. Add it to your Cargo.toml with the feature flags you need — v4 for random IDs is the most common — then call Uuid::new_v4() for a fully RFC 4122-compliant identifier. Below you'll find copy-paste ready code for generating a Rust UUID, parsing a string back into a Uuid, and the alternate feature-flagged generation methods the crate ships with.
How to Generate a UUID in Rust
The most common way to generate a UUID in Rust is Uuid::new_v4() from the uuid crate, which produces a random, cryptographically secure 128-bit identifier. Add the crate to Cargo.toml with the v4 feature enabled — no other setup required. For random bits, the python uuid function relies on os.urandom(), and the uuid module also ships uuid1() for timestamp-based values.
[dependencies]
uuid = { version = "1", features = ["v4"] }
use uuid::Uuid;
fn main() {
let my_uuid = Uuid::new_v4();
println!("{}", my_uuid);
// Output: 550e8400-e29b-41d4-a716-446655440000
}
Explanation
uuid = { version = "1", features = ["v4"] }in Cargo.toml pulls in only the v4 code path, keeping your compiled binary small.Uuid::new_v4()generates a random UUID using thegetrandomcrate under the hood, which draws from your OS's cryptographically secure random source.- The
{}format specifier callsUuid'sDisplayimplementation, printing the standard 36-character hyphenated form automatically. UuidimplementsCopy, so passing it around your codebase never requires cloning or borrowing.
Convert a String to a UUID in Rust
When a UUID arrives as a string — from a request body, a config file, or a database row — parse it back into a type-safe Uuid with Uuid::parse_str(). On PostgreSQL 13 and later, gen_random_uuid() works with no setup, as the postgresql uuid guide shows with short examples.
use uuid::Uuid;
fn main() {
let my_uuid = Uuid::new_v4();
let uuid_str = my_uuid.to_string();
// Parse the string back into a Uuid
let parsed = Uuid::parse_str(&uuid_str).expect("invalid UUID");
assert_eq!(my_uuid, parsed);
}
Explanation
Uuid::parse_str()returns aResult<Uuid, uuid::Error>, so invalid input never panics silently — handle theErrcase explicitly instead of calling.expect()in production code.- The parser accepts UUIDs with or without hyphens, in either uppercase or lowercase.
UuidimplementsPartialEq, so two parsed UUIDs compare equal with==when they represent the same value.- Use
Uuid::try_parse()(added in uuid 1.3) for a faster, allocation-free parse when you don't need detailed error messages.
Other Options for Generating UUIDs in Rust
The uuid crate supports every UUID version through Cargo feature flags, so you only compile in what you use. Enable v7 for a time-sortable UUID that improves database index performance, or v1 for a timestamp-plus-node-ID identifier. After install.packages finishes, UUIDgenerate() returns a character vector, which is the core of the r uuid examples for data analysis.
[dependencies]
uuid = { version = "1", features = ["v4", "v7", "serde"] }
use uuid::Uuid;
// Version 7 - Unix timestamp + random, sortable and index-friendly
let uuid_v7 = Uuid::now_v7();
// Version 1 - timestamp + node ID (needs an explicit context/clock source)
// let uuid_v1 = Uuid::new_v1(timestamp, &node_id);
Explanation
- Adding
"v7"to the features list unlocksUuid::now_v7(), which encodes the current Unix millisecond timestamp in the most significant bits — ideal for database primary keys. "v1"unlocksUuid::new_v1(), which needs an explicit timestamp and node ID source since Rust has no implicit "current MAC address" API.- Adding
"serde"derivesSerialize/DeserializeforUuid, so it works directly in any serde-compatible format (JSON, MessagePack, etc.) without a manual wrapper type. - Only enable the features you actually use — each one adds a small amount to your compiled binary size.