std-method

Duration::checked_sub: reject negative intervals

Calculate a remaining interval only when the minuend is at least the subtrahend. None indicates that the requested subtraction would be negative; decide explicitly whether this is an error or expired budget. Expected stdout (not executed): 275 true Common mistake: Subtracting an elapsed interval larger than the budget with the minus operator.

Formal Syntax & Structure

rust syntaxrust
d.checked_sub(rhs: Duration) -> Option<Duration>

Working Example

Example Snippetrust
fn main() {    use std::time::Duration;    let budget = Duration::from_millis(400);    println!("{}", budget.checked_sub(Duration::from_millis(125)).unwrap().as_millis());    println!("{}", budget.checked_sub(Duration::from_millis(401)).is_none());}
Rust Reference