Sub topic 15
Working with Option and ownership: as_ref, as_mut, take
This chapter assumes you know ownership and borrowing, how match and if let work, and the basics of Option<T>. Here you will see how to look inside an Option without consuming it.
The problem: matching moves the value
An Option<String> owns its String. If you match on it by value, the String moves out and the Option can't be used again.
fn main() {
let name: Option<String> = Some(String::from("Ferris"));
if let Some(s) = name {
println!("hello {s}");
}
// println!("{name:?}"); // error: borrow of partially moved value
}The commented line fails to compile because s took ownership of the string. The methods below avoid this.
as_ref: borrow the contents
as_ref turns &Option<T> into Option<&T>. The original stays intact, and you work with a shared reference to the inner value.
fn main() {
let name: Option<String> = Some(String::from("Ferris"));
let len = name.as_ref().map(|s| s.len()).unwrap_or(0);
println!("{len}");
println!("{name:?}");
}This prints 6 and then Some("Ferris"). Without as_ref, the map call would consume name.
as_mut: borrow the contents mutably
as_mut turns &mut Option<T> into Option<&mut T>. Use it to change the inner value in place.
fn main() {
let mut name: Option<String> = Some(String::from("Ferris"));
if let Some(s) = name.as_mut() {
s.push_str(" the crab");
}
println!("{name:?}");
}The output is Some("Ferris the crab").
take: move the value out and leave None
take replaces the Option with None and returns the old value. It needs &mut self, so the variable must be declared mut. It is useful when you must own the value but only hold a mutable reference to the Option, such as a field of a struct.
fn main() {
let mut slot: Option<String> = Some(String::from("job-1"));
if let Some(s) = slot.as_ref() {
println!("peek: {s}");
}
let taken = slot.take();
println!("{taken:?} {slot:?}");
}This prints peek: job-1, then Some("job-1") None.
Choosing between them
| Goal | Method | Result type | Original afterwards |
|---|---|---|---|
| Read the value | `as_ref` | `Option<&T>` | Unchanged |
| Modify the value in place | `as_mut` | `Option<&mut T>` | Unchanged, possibly modified |
| Take ownership | `take` | `Option<T>` | `None` |
Common errors
- Calling
takeon a variable not declaredmut. The compiler reports that it cannot borrow as mutable. - Forgetting
as_refbeforemapand then using theOptionagain. The compiler reports a use of a moved value. - Expecting
taketo leave the value in place. After the call, the original isNone.
Exercise
A struct has a field pending: Option<String>. In a method taking &mut self, you want to send the string to another function that takes String and leave the field empty. Which method do you use, and why not a plain match self.pending?
Show answer
Use self.pending.take(). It moves the String out and leaves None in the field. A plain match self.pending would try to move the value out of a borrowed struct, and the compiler rejects that because self is only borrowed.