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.
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
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.
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.
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
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 ofself.headwhich 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. takeismem::replace(&mut opt, None). The same idea works for any type withmem::takewhen the type has aDefault.- Use
insertwhen you want to overwrite and then edit. It always replaces the old contents, even if the option was alreadySome. If you want to keep an existing value, useget_or_insert_with. - Lazy initialization:
get_or_insert_withis a compact "compute once, then reuse" pattern for anOptionfield; for shared or thread-safe versions seeOnceLock. takeon aCopyoption still resets the original toNone. If you only want to read the value, just copy the option or useas_ref.take_ifneeds&mut Tin the predicate, so you can inspect or even adjust the value before deciding.- State machines: storing the state in an
Option<State>and callingtake()at the start ofstep(&mut self)lets you consume the old state by value and put the next one back.
Related
Option<T>,as_ref,as_mut,as_deref, map and and_then,std::mem- Lessons: Option, Ownership