3

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?

Psidom
  • 195,464
  • 25
  • 298
  • 322

1 Answers1

4

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 v.push(4) without first borrowing v. The same restriction would apply to fields, so if a struct contained a vector, you'd be unable to call container.vec.push(element) without first borrowing container.vec (even if container itself was already a 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.

user4815162342
  • 124,516
  • 15
  • 228
  • 298