Code guide

Generate UUIDs in Rust

Generate UUIDs in Rust with the uuid crate, including UUID v4, UUID v7, parsing and feature flags.

Rust generates UUIDs with the uuid crate. Because the crate is modular, you enable the versions you need through Cargo feature flags, then call the matching constructor.

Key takeaways

  • Add the uuid crate with the v4 and/or v7 features.
  • Uuid::new_v4() is random; Uuid::now_v7() is time-ordered.
  • Parse strings with Uuid::parse_str and handle the Result.

Add the crate and generate

Enable only the features you use. UUID v4 needs the v4 feature; UUID v7 needs v7. This keeps builds lean.

# Cargo.toml
[dependencies]
uuid = { version = "1", features = ["v4", "v7"] }

Create and parse UUIDs

Generate a random or time-ordered UUID, then parse untrusted input with parse_str, which returns a Result you should handle.

use uuid::Uuid;

fn main() {
    let v4 = Uuid::new_v4();        // random
    let v7 = Uuid::now_v7();        // time-ordered
    println!("{v4}");
    println!("{v7}");

    let parsed = Uuid::parse_str("018f2f7a-07b2-7d6e-9c37-43e1577b8b44");
    assert!(parsed.is_ok());
}

FAQ

Generate UUIDs in Rust questions

Which uuid crate features do I need?

Enable v4 for random UUIDs and v7 for time-ordered UUIDs. Each version constructor is gated behind its feature flag.

Is Uuid::new_v4 cryptographically random?

It uses the getrandom crate for secure randomness, which is appropriate for identifiers.

How do I validate a UUID string in Rust?

Call Uuid::parse_str and check the Result. It rejects malformed input for you.

Generate UUID in Rust - uuid Crate Examples