std-method

Option::take / take_if / replace

Move the old payload out, optionally only after a predicate, or replace it with a new payload. take_if allows the predicate to mutate the payload even when it returns false. Expected stdout (not executed): Some(3) None None Common mistake: Assuming take_if leaves data unchanged when the predicate fails.

Formal Syntax & Structure

rust syntaxrust
fn take(&mut self) -> Option<T>; fn take_if<P: FnOnce(&mut T) -> bool>(&mut self, predicate: P) -> Option<T>; fn replace(&mut self, value: T) -> Option<T>

Working Example

Example Snippetrust
fn main() {    let mut job = Some(3);    let old = job.take_if(|n| *n > 2);    println!("{old:?} {job:?}");    println!("{:?}", job.replace(8));}
Rust Reference