Rust’s uuid crate is the standard library for UUID generation, with over 70 million downloads. Version 1.x added UUID v7 support via Uuid::now_v7(), making the upgrade from v4 straightforward.
Adding the uuid Crate
# Cargo.toml
[dependencies]
uuid = { version = "1", features = ["v4", "v7", "serde"] }
Feature flags control what is compiled in:
| Feature | Purpose |
|---|---|
v4 | Enable Uuid::new_v4() |
v7 | Enable Uuid::now_v7() |
serde | Derive Serialize/Deserialize |
fast-rng | Use a faster (but still cryptographically adequate) RNG |
Generating UUIDs
use uuid::Uuid;
// UUID v4 — random
let id_v4 = Uuid::new_v4();
println!("{}", id_v4); // e.g. "550e8400-e29b-41d4-a716-446655440000"
// UUID v7 — time-ordered
let id_v7 = Uuid::now_v7();
println!("{}", id_v7); // e.g. "018fbe3a-4c5d-7000-8abc-0123456789ab"
Uuid::now_v7() reads the system clock via std::time::SystemTime::now() and generates 74 random bits for the remaining fields. The timestamp uses Unix milliseconds in the high 48 bits, conforming to RFC 9562.
Diesel Integration (PostgreSQL)
Diesel maps Uuid from the uuid crate to PostgreSQL’s uuid column type:
[dependencies]
diesel = { version = "2", features = ["postgres", "uuid"] }
uuid = { version = "1", features = ["v7"] }
use diesel::prelude::*;
use uuid::Uuid;
#[derive(Insertable)]
#[diesel(table_name = orders)]
pub struct NewOrder {
pub id: Uuid,
pub customer_id: Uuid,
}
fn create_order(conn: &mut PgConnection, customer_id: Uuid) -> QueryResult<usize> {
let new_order = NewOrder {
id: Uuid::now_v7(),
customer_id,
};
diesel::insert_into(orders::table)
.values(&new_order)
.execute(conn)
}
No schema migration needed when switching from v4 to v7 — the uuid column type in PostgreSQL stores both versions identically as 16 bytes.
SQLx Integration
SQLx also supports the Uuid type natively:
[dependencies]
sqlx = { version = "0.8", features = ["postgres", "uuid", "runtime-tokio"] }
uuid = { version = "1", features = ["v7"] }
let id = Uuid::now_v7();
sqlx::query!("INSERT INTO orders (id) VALUES ($1)", id)
.execute(&pool)
.await?;
SQLx encodes the Uuid as PostgreSQL’s native uuid type via the encode trait — no manual conversion required.
Serde Serialization
With the serde feature enabled, Uuid derives Serialize and Deserialize automatically, serializing to the standard hyphenated string format:
use serde::{Deserialize, Serialize};
use uuid::Uuid;
#[derive(Serialize, Deserialize)]
struct OrderResponse {
id: Uuid, // serializes as "018fbe3a-4c5d-7000-8abc-0123456789ab"
total: f64,
}
For compact JSON or binary formats, the uuid crate also supports serializing as a 16-byte array via uuid::serde::compact.
Related Resources
- uuid crate on crates.io
- uuid crate documentation
- Diesel ORM documentation
- SQLx — async Rust SQL toolkit
Frequently asked questions
How do I generate UUID v7 in Rust?
Use the uuid crate with the v7 feature: uuid = { version = "1", features = ["v7"] }. Then call Uuid::now_v7(). For Diesel or SQLx integration, also enable the uuid feature on those crates — they map Uuid to the PostgreSQL uuid column type automatically.
Do UUIDs hurt database index performance?
UUID v4 does — its randomness causes every insert to land at a different leaf page, leading to page splits and poor cache locality. UUID v7 embeds a millisecond timestamp so consecutive inserts cluster together, behaving like an auto-increment integer for B-tree purposes.
Should I use v4 or v7?
Use v7 for database primary keys (time-sortable, index-friendly) and v4 for anything where creation order could leak information, like tokens or share links.
How do I generate a UUID in Rust?
Use the uuid crate. Add it to Cargo.toml with the features you need: uuid = { version = "1", features = ["v4", "v7"] }. Then call Uuid::new_v4() or Uuid::now_v7(). The crate uses the platform CSPRNG for randomness and the system clock for v7 timestamps.
Does Diesel support UUID primary keys in Rust?
Yes. Diesel supports the Uuid type from the uuid crate when you enable the uuid feature in the diesel crate: diesel = { version = "2", features = ["postgres", "uuid"] }. Map your struct field as id: Uuid and Diesel handles the PostgreSQL uuid column type automatically.