Generate a UUID in Rust

How to generate a UUID in Rust with the uuid crate: enable the v4 and v7 features, Uuid::new_v4 and Uuid::now_v7, name based v5, parsing, the simple and braced formats, and serde and sqlx integration.

Try it here

Generate a UUID to paste into your Rust code, in any version and format.

Format

Your UUIDs

Copy one, copy them all, or download the list. The format options above apply to everything shown here.

    The uuid crate

    # Cargo.toml
    [dependencies]
    uuid = { version = "1", features = ["v4", "v7", "v5", "serde"] }
    
    use uuid::Uuid;
    
    let id  = Uuid::new_v4();                                  // random
    let id7 = Uuid::now_v7();                                  // time ordered, use for keys
    let id5 = Uuid::new_v5(&Uuid::NAMESPACE_DNS, b"example.com");   // name based
    
    id.to_string();          // "f47ac10b-58cc-4372-a567-0e02b2c3d479"
    id.as_bytes();           // &[u8; 16]

    Each version is behind a Cargo feature so the crate stays small. Forgetting the feature gives a "no function named new_v4" error, which is the first thing to check. The crate uses getrandom, so it is secure and works on every target including wasm.

    Formats

    id.hyphenated().to_string();   // f47ac10b-58cc-4372-a567-0e02b2c3d479   default
    id.simple().to_string();       // f47ac10b58cc4372a5670e02b2c3d479       32 hex
    id.braced().to_string();       // {f47ac10b-58cc-4372-a567-0e02b2c3d479}
    id.urn().to_string();          // urn:uuid:f47ac10b-58cc-4372-a567-0e02b2c3d479
    format!("{:X}", id.simple());  // uppercase

    Parse and validate

    let parsed = Uuid::parse_str("f47ac10b-58cc-4372-a567-0e02b2c3d479")?;
    let parsed: Uuid = "f47ac10b-58cc-4372-a567-0e02b2c3d479".parse()?;
    
    parsed.get_version();       // Some(Version::Random)
    parsed.get_version_num();   // 4
    parsed.is_nil();
    Uuid::nil();                // 00000000-0000-0000-0000-000000000000
    Uuid::max();                // ffffffff-ffff-ffff-ffff-ffffffffffff
    
    // read the timestamp back from a v7
    if let Some(ts) = id7.get_timestamp() {
        let (secs, nanos) = ts.to_unix();
    }

    parse_str accepts hyphenated, simple, braced and urn forms in either case. It rejects anything with the wrong length or non hex characters.

    serde, sqlx and axum

    #[derive(Serialize, Deserialize)]
    struct Order {
        id: Uuid,        // serialises as the hyphenated string with the serde feature
    }
    
    // sqlx with the "uuid" feature maps Uuid to PostgreSQL uuid columns
    let row = sqlx::query!("INSERT INTO orders (id) VALUES ($1) RETURNING id", Uuid::now_v7())
        .fetch_one(&pool).await?;
    
    // axum path extractor parses it for you
    async fn get_order(Path(id): Path<Uuid>) { }

    Mistakes to avoid

    • Missing Cargo features. v4, v7 and serde are all opt in.
    • Building ids from rand::random. The crate already uses a secure source and sets the version bits correctly.
    • Storing to_string() in a bytea or BINARY(16) column. Use as_bytes() there, and to_string() only for text columns and APIs.

    Frequently asked questions

    Which Cargo features do I need for the uuid crate?

    v4 for random, v7 for time ordered, v5 or v3 for name based, serde for serialisation. Add js when targeting wasm in the browser on older versions of the crate.

    How do I generate a UUID v7 in Rust?

    Uuid::now_v7() with the v7 feature enabled. Uuid::new_v7(Timestamp) lets you supply the time yourself.

    Is Uuid::new_v4 cryptographically secure?

    Yes. It uses the getrandom crate, which reads from the operating system's secure source on every supported platform.

    ↑ Top
    Copied!