2

I'm confused why the function get works with both Vec<T> and &Vec<T>. I know that &Vec<T> automatically converts to &[T] so in some sense, the question is why it works on Vec<T> as well as &[T]. Obviously, get works with &[T], so is it separately implemented for Vec<T> in addition to the implementation for &[T]? Looking at the docs, it doesn't seem like it, there is only one get implementation: https://doc.rust-lang.org/std/vec/struct.Vec.html#method.get

In the following code, get is acting on Vec<T>.

fn first<T: PartialOrd + Copy>(list: Vec<T>) -> T {
    *list.get(0).unwrap()
}

fn main() {
    let number_list = vec![34, 50, 25, 100, 65];
    let result = first(number_list);
    println!("The first number is {}", result);
}

In this code, it is acting on &Vec<T> (aka &[T]):

fn first<T: PartialOrd + Copy>(list: &Vec<T>) -> T {
    *list.get(0).unwrap()
}

fn main() {
    let number_list = vec![34, 50, 25, 100, 65];
    let result = first(&number_list);
    println!("The first number is {}", result);
}
Schwern
  • 153,029
  • 25
  • 195
  • 336
fraiser
  • 929
  • 12
  • 28

1 Answers1

5

This is due to automatic referencing.

From Method Syntax in The Rust Programming Language...

Rust has a feature called automatic referencing and dereferencing [...] when you call a method with object.something(), Rust automatically adds in &, &mut, or * so object matches the signature of the method. In other words, the following are the same:

p1.distance(&p2);
(&p1).distance(&p2);

The first one looks much cleaner. This automatic referencing behavior works because methods have a clear receiver—the type of self. Given the receiver and name of a method, Rust can figure out definitively whether the method is reading (&self), mutating (&mut self), or consuming (self). The fact that Rust makes borrowing implicit for method receivers is a big part of making ownership ergonomic in practice.

IInspectable
  • 46,945
  • 8
  • 85
  • 181
Schwern
  • 153,029
  • 25
  • 195
  • 336