Search code examples
rustoption-type

Understand rust Option as_mut method


Given a rust option:

let mut x = Some(3);

Why can I directly call x.as_mut()? As I can see from the doc, as_mut is defined as:

pub fn as_mut(&mut self) -> Option<&mut T> Converts from &mut Option to Option<&mut T>.

which expects the first parameter to be &mut self, i.e. &mut Option<T>. Shouldn't I use (&mut x).as_mut() instead?


Solution

  • Here Rust's . operator does what you mean and implicitly borrows the variable. If it didn't, working with non-borrowed values would be annoying, because a value declared as e.g. let mut v = vec![1, 2, 3] couldn't be manipulated with e.g. v.push(4) without writing (&mut v).push(4). The same would apply to fields, so if a struct contained a vector, you'd be unable to call container.vec.push(element) without explicitly borrowing container.vec, even if container itself was itself a mutable reference.

    To prevent such noise C has two operators for field access, . and ->, where the latter automatically dereferences. Rust's . intentionally goes ahead and does the borrowing or dereferencing needed for the method call to work.