Appearance
Generate UUID in Rust
The standard way to generate UUIDs in Rust is using the uuid crate. Here's how to generate a random UUID version 4:
rust
use uuid::Uuid;
fn main() {
// Generate UUID version 4 - random
let id = Uuid::new_v4();
println!("Generated UUID: {}", id);
}
For generating specific UUID versions, the uuid crate provides comprehensive support with feature flags:
rust
use uuid::Uuid;
fn main() {
// Generate UUID version 1 - time based (requires "v1" feature)
#[cfg(feature = "v1")]
{
let uuid1 = Uuid::now_v1(&[1, 2, 3, 4, 5, 6]);
println!("UUID v1: {}", uuid1);
}
// Generate UUID version 3 - deterministic and hashed with MD5 (requires "v3" feature)
#[cfg(feature = "v3")]
{
let namespace = Uuid::NAMESPACE_URL;
let uuid3 = Uuid::new_v3(&namespace, b"https://example.com");
println!("UUID v3: {}", uuid3);
}
// Generate UUID version 4 - random (default feature)
let uuid4 = Uuid::new_v4();
println!("UUID v4: {}", uuid4);
// Generate UUID version 5 - deterministic and hashed with SHA-1 (requires "v5" feature)
#[cfg(feature = "v5")]
{
let namespace = Uuid::NAMESPACE_URL;
let uuid5 = Uuid::new_v5(&namespace, b"https://example.com");
println!("UUID v5: {}", uuid5);
}
// Generate UUID version 6 - time-ordered (requires "v6" feature)
#[cfg(feature = "v6")]
{
let uuid6 = Uuid::now_v6(&[1, 2, 3, 4, 5, 6]);
println!("UUID v6: {}", uuid6);
}
// Generate UUID version 7 - time-ordered with random (requires "v7" feature)
#[cfg(feature = "v7")]
{
let uuid7 = Uuid::now_v7();
println!("UUID v7: {}", uuid7);
}
}
Installation & Setup
Add to Cargo.toml:
toml
[dependencies]
uuid = { version = "1.6", features = ["v4", "fast-rng", "macro-diagnostics"] }
# For specific versions, add features:
# uuid = { version = "1.6", features = ["v1", "v3", "v4", "v5", "v6", "v7", "fast-rng"] }
Available Features:
v1
- Time-based UUIDsv3
- MD5 namespace-based UUIDsv4
- Random UUIDs (most common)v5
- SHA-1 namespace-based UUIDsv6
- Time-ordered UUIDsv7
- Modern time-based UUIDsfast-rng
- Faster random number generationserde
- Serialization support
Advanced Usage
Parse and Validate UUIDs:
rust
use uuid::Uuid;
use std::str::FromStr;
fn main() {
// Parse UUID from string
let uuid_str = "550e8400-e29b-41d4-a716-446655440000";
match Uuid::from_str(uuid_str) {
Ok(uuid) => {
println!("Parsed UUID: {}", uuid);
println!("Version: {:?}", uuid.get_version());
println!("Variant: {:?}", uuid.get_variant());
}
Err(e) => println!("Invalid UUID: {}", e),
}
// Using parse method
let uuid: Result<Uuid, _> = uuid_str.parse();
match uuid {
Ok(u) => println!("Parsed: {}", u),
Err(e) => println!("Error: {}", e),
}
}
Custom Namespace UUIDs:
rust
use uuid::Uuid;
fn main() {
// Create custom namespace
let custom_namespace = Uuid::parse_str("6ba7b810-9dad-11d1-80b4-00c04fd430c8")
.expect("Invalid namespace UUID");
#[cfg(feature = "v5")]
{
// Generate deterministic UUIDs
let uuid5 = Uuid::new_v5(&custom_namespace, b"my-resource");
println!("Custom namespace UUID: {}", uuid5);
}
}
Web Services & Async Usage
With Tokio and Serde:
rust
use uuid::Uuid;
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize)]
struct Resource {
id: Uuid,
name: String,
}
impl Resource {
fn new(name: String) -> Self {
Self {
id: Uuid::new_v4(),
name,
}
}
}
#[tokio::main]
async fn main() {
let resource = Resource::new("example".to_string());
println!("Resource: {}", serde_json::to_string(&resource).unwrap());
}
UUID Version Comparison
Choose the right version for your Rust application:
- Version 1 - Time-based, includes MAC address
- Version 3 - MD5 namespace-based, deterministic
- Version 4 - Random, most popular choice
- Version 5 - SHA-1 namespace-based, more secure than v3
- Version 6 - Time-ordered, better than v1 for databases
- Version 7 - Modern time-based with improved sorting
For Rust applications:
- Web services: Use Version 4 for API tokens and session IDs
- Database applications: Consider Version 7 for optimal indexing
- System tools: Use Version 1 for time-based tracking
How do I generate UUID in other languages?
Systems programming:
Web development:
- JavaScript - crypto.randomUUID() & uuid library
- Python - Built-in uuid module
- Java - java.util.UUID & UuidCreator
- C# - System.Guid & UuidCreator