Skip to content
Tutorials Center
My learning

Topics

Rust Reference ยท Option and Result

Option take, replace and insert

Reference for Rust Option::take, replace, insert, get_or_insert_with and take_if: moving a value out of an Option behind a mutable reference.

You cannot move a value out of a field that sits behind a &mut reference and simply leave a hole, because Rust requires every field to hold a valid value at all times. Option::take solves this for optional fields: it hands you the old contents as an owned Option<T> and leaves None in its place. replace does the same but puts a new Some(value) back.

These methods are the standard tool for linked lists, state machines, "consume once" fields and lazily filled caches. They work through &mut self, so the Option must be stored in a mutable place.

Rust
let mut slot = Some(5);
let old = slot.take();            // old == Some(5), slot == None
let prev = slot.replace(9);       // prev == None, slot == Some(9)

Try it

Rust take and replace

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Rust A linked stack built on take

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Rust take_if and get_or_insert_with

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Syntax

Rust
impl<T> Option<T> {
    pub const fn take(&mut self) -> Option<T>;
    pub const fn replace(&mut self, value: T) -> Option<T>;
    pub fn insert(&mut self, value: T) -> &mut T;
    pub fn get_or_insert(&mut self, value: T) -> &mut T;
    pub fn get_or_insert_with<F: FnOnce() -> T>(&mut self, f: F) -> &mut T;
    pub fn take_if<P: FnOnce(&mut T) -> bool>(&mut self, predicate: P) -> Option<T>;
}
Method Description
take() Returns the current value and leaves None.
replace(value) Stores Some(value) and returns what was there before (None if it was empty).
insert(value) Stores Some(value), drops any old value, and returns a &mut T to the new contents.
get_or_insert(value) If None, stores value; either way returns &mut T. The argument is evaluated eagerly.
get_or_insert_with(f) Like get_or_insert, but f only runs when the option is empty.
take_if(pred) Takes the value only when the predicate returns true; otherwise leaves it in place and returns None. Stable since Rust 1.80.

Returns: take, replace and take_if return the old value as an Option<T>; the insert family returns a mutable reference into the option.

Panics: none of these methods panic.

Usage notes

  • Why not just move the field? let v = self.head; fails with "cannot move out of self.head which is behind a mutable reference". self.head.take() is the idiomatic fix, and it costs no more than a pointer-sized copy plus a write.
  • take is mem::replace(&mut opt, None). The same idea works for any type with mem::take when the type has a Default.
  • Use insert when you want to overwrite and then edit. It always replaces the old contents, even if the option was already Some. If you want to keep an existing value, use get_or_insert_with.
  • Lazy initialization: get_or_insert_with is a compact "compute once, then reuse" pattern for an Option field; for shared or thread-safe versions see OnceLock.
  • take on a Copy option still resets the original to None. If you only want to read the value, just copy the option or use as_ref.
  • take_if needs &mut T in the predicate, so you can inspect or even adjust the value before deciding.
  • State machines: storing the state in an Option<State> and calling take() at the start of step(&mut self) lets you consume the old state by value and put the next one back.