Sub topic 15
Working with Option and ownership: as_ref, as_mut, take
This chapter assumes you know basic ownership and borrowing, how match and if let work on Option, and how closures are passed to methods like map. It covers what happens when an Option holds a value that is not Copy, such as a String or a Box. It also covers the three methods that handle those cases: as_ref, as_mut, and take.
The problem: matching moves the contents
Option<T> owns its T. If you pattern match on an Option by value and bind the inner value, the value moves out of the Option.
fn main() {
let name: Option<String> = Some(String::from("Ferris"));
if let Some(s) = name {
println!("hello {s}");
}
// Uncommenting the next line fails to compile:
// error[E0382]: borrow of partially moved value: `name`
// println!("{name:?}");
}The String moved into s, so name is no longer usable. This does not happen with Option<i32>. Option<T> is Copy when T is Copy, so matching copies the integer. The errors in this chapter only appear with owning types like String, Vec, and Box.
Rust offers three ways to avoid the move, depending on what you want:
- Look at the contents without taking them:
as_ref. - Change the contents in place:
as_mut. - Take the contents out and leave
Nonebehind:take.
as_ref: borrow the contents
as_ref takes &Option<T> and returns Option<&T>. The original Option is untouched, and you get a reference to what is inside.
fn main() {
let name: Option<String> = Some(String::from("Ferris"));
if let Some(s) = name.as_ref() {
println!("length {}", s.len());
}
let view: Option<&str> = name.as_deref();
println!("{view:?} {name:?}");
}This prints length 6, then Some("Ferris") Some("Ferris"). name is still usable at the end.
as_deref is as_ref plus a dereference. It turns Option<String> into Option<&str>, Option<Vec<T>> into Option<&[T]>, and Option<Box<T>> into Option<&T>. It is usually what you want when passing an optional string to a function that takes Option<&str>.
as_mut: modify the contents in place
as_mut takes &mut Option<T> and returns Option<&mut T>. Use it when the value should stay in the Option but change.
fn main() {
let mut log: Option<Vec<String>> = Some(Vec::new());
if let Some(lines) = log.as_mut() {
lines.push(String::from("start"));
lines.push(String::from("stop"));
}
println!("{log:?}");
}This prints Some(["start", "stop"]). Writing if let Some(lines) = &mut log gives the same result through match ergonomics. The method form is useful in chains, such as self.cache.as_mut().map(|c| c.clear()).
take: move out and leave None
Inside a method that has &mut self, you often want to move a field out of the struct. The compiler refuses, because that would leave the struct with a missing field.
struct Job {
id: u32,
}
struct Worker {
current: Option<Job>,
}
impl Worker {
// Does not compile:
// error[E0507]: cannot move out of `self.current` which is behind a mutable reference
// fn finish(&mut self) -> Option<Job> {
// self.current
// }
fn finish(&mut self) -> Option<Job> {
self.current.take()
}
}
fn main() {
let mut w = Worker { current: Some(Job { id: 7 }) };
let done = w.finish();
println!("{:?} {}", done.map(|j| j.id), w.current.is_none());
}This prints Some(7) true. take swaps the field with None and returns the old value, so the struct stays valid. Option::take is the same as std::mem::take(&mut opt), because Option<T> implements Default with None.
Related methods:
| Method | Receiver | Returns | What is left in the Option |
|---|---|---|---|
| `as_ref` | `&self` | `Option<&T>` | Unchanged |
| `as_mut` | `&mut self` | `Option<&mut T>` | Unchanged, but you can edit it |
| `as_deref` | `&self` | `Option<&T::Target>` | Unchanged |
| `take` | `&mut self` | `Option<T>` | `None` |
| `replace(v)` | `&mut self` | `Option<T>` (old value) | `Some(v)` |
| `get_or_insert_with(f)` | `&mut self` | `&mut T` | `Some(..)`, filled by `f` if it was `None` |
get_or_insert_with is a clean way to initialize lazily:
fn main() {
let mut cache: Option<Vec<u32>> = None;
let items = cache.get_or_insert_with(|| {
println!("building cache");
vec![1, 2, 3]
});
items.push(4);
let again = cache.get_or_insert_with(|| unreachable!());
println!("{again:?}");
}The closure runs once. The output is building cache, then [1, 2, 3, 4].
A worked example: a linked stack
Recursive types need Box, and an optional next pointer is Option<Box<Node>>. This is the standard place where all three methods appear together.
struct Node {
value: i32,
next: Option<Box<Node>>,
}
struct Stack {
head: Option<Box<Node>>,
}
impl Stack {
fn new() -> Self {
Stack { head: None }
}
fn push(&mut self, value: i32) {
let node = Box::new(Node { value, next: self.head.take() });
self.head = Some(node);
}
fn pop(&mut self) -> Option<i32> {
self.head.take().map(|node| {
self.head = node.next;
node.value
})
}
fn peek(&self) -> Option<&i32> {
self.head.as_ref().map(|node| &node.value)
}
fn peek_mut(&mut self) -> Option<&mut i32> {
self.head.as_mut().map(|node| &mut node.value)
}
}
fn main() {
let mut stack = Stack::new();
stack.push(1);
stack.push(2);
if let Some(top) = stack.peek_mut() {
*top += 10;
}
println!("{:?}", stack.peek());
println!("{:?}", stack.pop());
println!("{:?}", stack.pop());
println!("{:?}", stack.pop());
}The output is Some(12), Some(12), Some(1), None.
- In
push,takemoves the old head into the new node and leavesNoneinself.head. Then the new node becomes the head. - In
pop,takeremoves the head. If the list is empty,takereturnsNoneandmapdoes nothing. peekandpeek_mutuseas_refandas_mut, so the stack keeps its nodes and the caller gets only a borrow.
Common mistakes
- Using
unwrapon a field.self.name.unwrap()tries to move out ofself. Useself.name.as_ref().unwrap(), or better, handle theNonecase. - Forgetting that
takechanges state. Callingtaketwice returnsSomeonce andNonethe second time. If you only want to look, useas_ref. - Expecting
as_refto give&str. It givesOption<&String>. Useas_derefwhen a function needsOption<&str>. - Holding a borrow too long. The reference from
as_reforas_mutkeeps theOptionborrowed. You cannot calltakeon it until that reference is no longer used.
Exercise
A struct has title: Option<String>. Write a method fn title_len(&self) -> usize that returns the length of the title, or 0 if there is none, without moving the string out of self.
Show answer
Use as_ref (or as_deref) so that self.title is only borrowed: fn title_len(&self) -> usize { self.title.as_deref().map(str::len).unwrap_or(0) }. Calling self.title.map(...) directly would not compile, because it would move the String out of a shared reference.
Exercise
In the Stack example, pop uses self.head.take().map(...). What would go wrong if pop were written as self.head.map(|node| { self.head = node.next; node.value })?
Show answer
It fails to compile with "cannot move out of self.head which is behind a mutable reference". map takes self by value, so it would move the field out of &mut self. take first replaces the field with None and hands the old value to map, so self.head stays valid.