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 native UUID column type and gen_random_uuid() support, see the postgresql uuid guide.
[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(). To generate uuid online securely, the tool uses the Web Crypto API so every output is cryptographically random.
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. Use the c++ uuid guide to implement UUID generation in C++ with Boost.UUID or the platform-native APIs.
[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.