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.
For implementation context, continue with UUID v4, UUID v7, and Go. These pages cover the closest generator, comparison, validation or storage decisions without repeating this guide.
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());
}Propagate parsing failures instead of panicking
Use the question-mark operator to return a parsing error to the caller. unwrap() and expect() are convenient in tests, but malformed request input should produce a controlled error rather than terminating a request handler.
Keep Uuid as a typed value inside the application. Use hyphenated text for JSON and logs, or as_bytes() for a protocol that explicitly expects the 16-byte representation. Enable the serde feature separately when integrating with Serde.
fn normalize_uuid(input: &str) -> Result<String, uuid::Error> {
let id = Uuid::parse_str(input)?;
Ok(id.hyphenated().to_string())
}