std-method
Atomic swap: replace and retrieve previous value
Swap is one read-modify-write operation. It returns the value present immediately before the replacement in that atomic object’s modification order. Expected stdout (not executed): 5 9 Common mistake: Expecting swap to return the newly stored value.
Formal Syntax & Structure
rust syntaxrust
value.swap(new: usize, order: Ordering) -> usizeWorking Example
Example Snippetrust
fn main() { use std::sync::atomic::{AtomicUsize, Ordering}; let n = AtomicUsize::new(5); let old = n.swap(9, Ordering::AcqRel); println!("{} {}", old, n.load(Ordering::Relaxed));}