Rust

Rust provides UUID generation through the uuid crate, which offers cryptographically secure, RFC 4122 compliant UUID generation with zero-cost abstractions.

Add uuid Crate to Cargo.toml

[dependencies]
uuid = { version = "1.6", features = ["v4", "fast-rng"] }

Basic Usage (UUID v4)

use uuid::Uuid;

fn main() {
    // Generate a random UUID (version 4)
    let id = Uuid::new_v4();
    println!("{}", id);
    // Output: f47ac10b-58cc-4372-a567-0e02b2c3d479
}

Different UUID Versions

use uuid::Uuid;

fn main() {
    // UUID v4 (random)
    let v4 = Uuid::new_v4();
    println!("UUID v4: {}", v4);
    
    // UUID v5 (name-based with SHA-1)
    let namespace = Uuid::NAMESPACE_DNS;
    let v5 = Uuid::new_v5(&namespace, b"example.com");
    println!("UUID v5: {}", v5);
    
    // Parse from string
    let parsed = Uuid::parse_str("f47ac10b-58cc-4372-a567-0e02b2c3d479")
        .expect("Invalid UUID");
    println!("Parsed: {}", parsed);
}

UUID in Structs with Serde

use serde::{Deserialize, Serialize};
use uuid::Uuid;

#[derive(Debug, Serialize, Deserialize)]
struct User {
    id: Uuid,
    name: String,
}

fn main() {
    let user = User {
        id: Uuid::new_v4(),
        name: "John Doe".to_string(),
    };
    
    // Serialize to JSON
    let json = serde_json::to_string(&user).unwrap();
    println!("{}", json);
    // Output: {"id":"f47ac10b-58cc-4372-a567-0e02b2c3d479","name":"John Doe"}
}

Useful Methods

use uuid::Uuid;

fn main() {
    let id = Uuid::new_v4();
    
    // Different string formats
    println!("Standard: {}", id);                    // Hyphenated
    println!("Hyphenated: {}", id.hyphenated());     // Explicit
    println!("Simple: {}", id.simple());             // No hyphens
    println!("URN: {}", id.urn());                   // As URN
    
    // Get raw bytes
    let bytes = id.as_bytes();
    println!("Bytes: {:?}", bytes);
    
    // Version and variant
    println!("Version: {:?}", id.get_version());
    println!("Variant: {:?}", id.get_variant());
}

Cargo.toml Features

[dependencies]
uuid = { 
    version = "1.6", 
    features = [
        "v4",        # UUID version 4 (random)
        "v5",        # UUID version 5 (SHA-1 name-based)
        "fast-rng",  # Fast random number generation
        "serde",     # Serialization support
    ] 
}

Documentation: docs.rs/uuid

*uuid crate conforms to RFC 4122 UUID specification*