How to generate a random UUID in Rust?
To create a new random (V4) UUID and print it out in hexadecimal form we can use uuid create and functionnew_v4()
:use uuid::Uuid;
fn main() {
let my_uuid = Uuid::new_v4();
println!("{}", my_uuid);
Ok(())
}
Another way to generate a UUID
use uuid::Uuid;
fn main() -> Result<(), Box<dyn std::error::Error>> {
#[cfg(feature = "v4")] {
let my_uuid = Uuid::new_v4()?;
println!("{}", my_uuid);
}
Ok(())
}
Examples of string representations:
- simple: 936DA01F9ABD4d9d80C702AF85C822A8
- hyphenated: 550e8400-e29b-41d4-a716-446655440000
- urn: urn:uuid:F9168C5E-CEB2-4faa-B6BF-329BF39FA1E4