Skip to main content

How to Generate UUID in Rust

Using uuid crate

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. To generate uuid online securely, the tool uses the Web Crypto API so every output is cryptographically random.

Generate UUID in Rust

Uuid::new_v4()
550e8400-e29b-41d4-a716-446655440000

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.

Cargo.toml
[dependencies]
uuid = { version = "1", features = ["v4"] }
main.rs
use uuid::Uuid;

fn main() {
    let my_uuid = Uuid::new_v4();
    println!("{}", my_uuid);
    // Output: 550e8400-e29b-41d4-a716-446655440000
}

Explanation

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.

main.rs
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

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.

Cargo.toml
[dependencies]
uuid = { version = "1", features = ["v4", "v7", "serde"] }
main.rs
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

Comments & Feedback

Share your experience or ask questions about this tool

Copied!