std-method
Atomic fetch_add and fetch_sub: wrapping updates
Each operation updates an integer and returns its previous value. Atomic integer addition and subtraction wrap on overflow or underflow; this is independent of debug-profile ordinary integer overflow checks. Expected stdout (not executed): true 0 true Common mistake: Expecting atomic arithmetic to saturate or return an overflow error.
Formal Syntax & Structure
rust syntaxrust
n.fetch_add(delta, order); n.fetch_sub(delta, order)Working Example
Example Snippetrust
fn main() { use std::sync::atomic::{AtomicUsize, Ordering::Relaxed}; let n = AtomicUsize::new(usize::MAX); println!("{}", n.fetch_add(1, Relaxed) == usize::MAX); println!("{}", n.load(Relaxed)); n.fetch_sub(1, Relaxed); println!("{}", n.load(Relaxed) == usize::MAX);}