std-method

Instant::checked_add and checked_sub

Create a deadline or earlier reading if the target instant is representable on the platform. A valid Duration does not guarantee a valid Instant. Prefer checked arithmetic when constructing deadlines from external inputs. Expected stdout (not executed): true Common mistake: Assuming the same huge offset works on every operating system.

Formal Syntax & Structure

rust syntaxrust
instant.checked_add(duration: Duration) -> Option<Instant>; instant.checked_sub(duration) -> Option<Instant>

Working Example

Example Snippetrust
fn main() {    use std::time::{Duration, Instant};    let base = Instant::now();    let step = Duration::from_secs(1);    let deadline = base.checked_add(step).unwrap();    println!("{}", deadline.checked_sub(step) == Some(base));}
Rust Reference