How to Generate UUIDs in Rust

Use the `uuid` crate with the `v4` feature to generate random UUIDs, or `v7` for time-ordered ones.

Use the uuid crate with the v4 feature to generate random UUIDs, or v7 for time-ordered ones. You can create a UUID directly via Uuid::new_v4() and convert it to a string or bytes as needed.

Add the dependency to your Cargo.toml:

[dependencies]
uuid = { version = "1.11", features = ["v4"] }

Here is a practical example generating a random UUID and printing it in standard format:

use uuid::Uuid;

fn main() {
    // Generate a random UUID (v4)
    let my_uuid = Uuid::new_v4();
    
    // Print as a string (e.g., "550e8400-e29b-41d4-a716-446655440000")
    println!("Generated UUID: {}", my_uuid);
    
    // Convert to a byte array if needed for storage or hashing
    let bytes: [u8; 16] = my_uuid.as_bytes();
    println!("Bytes: {:?}", bytes);
}

If you need a time-ordered UUID (v7) which is better for database indexing, enable the v7 feature in Cargo.toml and use Uuid::now_v7():

// Cargo.toml: uuid = { version = "1.11", features = ["v7"] }
use uuid::Uuid;

fn main() {
    let time_uuid = Uuid::now_v7();
    println!("Time-ordered UUID: {}", time_uuid);
}

The uuid crate handles all the complexity of RFC 4122 compliance, ensuring uniqueness across systems without requiring external services. For most applications, v4 is sufficient, but v7 is preferred when you need the UUIDs to be sortable by creation time.