Use std::time::Duration to represent a span of time as nanoseconds, providing a type-safe way to handle timeouts, delays, and time arithmetic without manual unit conversion. You create instances using the new constructor or helper methods like from_secs and from_millis, then pass them to blocking or async operations that require a time limit.
Here is a practical example of creating a duration and using it with a blocking sleep and a timeout on a channel:
use std::time::Duration;
use std::thread;
use std::sync::mpsc;
fn main() {
// Create a duration of 2 seconds and 500 milliseconds
let timeout = Duration::from_secs(2) + Duration::from_millis(500);
// Blocking sleep
println!("Sleeping for {:?}", timeout);
thread::sleep(timeout);
// Using Duration with channel timeout
let (tx, rx) = mpsc::channel();
// Spawn a thread that sends a message after 1 second
thread::spawn(move || {
thread::sleep(Duration::from_secs(1));
let _ = tx.send("Hello");
});
// Wait for the message with a 3-second timeout
match rx.recv_timeout(Duration::from_secs(3)) {
Ok(msg) => println!("Received: {}", msg),
Err(_) => println!("Timeout reached"),
}
}
You can also perform arithmetic on durations, such as adding, subtracting, or multiplying them, which is useful for calculating deadlines or backoff strategies. Note that Duration represents a non-negative span of time; if you need to represent a point in time or handle negative intervals, you should use std::time::SystemTime or std::time::Instant instead.
For async code, the tokio and async-std runtimes accept Duration directly in their sleep and timeout functions:
use tokio::time::{sleep, Duration};
#[tokio::main]
async fn main() {
let delay = Duration::from_millis(500);
println!("Waiting...");
sleep(delay).await;
println!("Done!");
}
When working with Duration, always prefer the helper methods (from_secs, from_millis, from_micros, from_nanos) over the raw new(secs, nanos) constructor unless you need to construct a duration from specific components. This reduces the risk of unit errors and makes the code more readable. Remember that Duration is immutable, so operations like + or - return a new Duration rather than modifying the original.