2

I check Index trait in doc and find return type of index() is &T.

Then I write this function to get value from vector:

fn get_value_test(a: usize, v: &Vec<i32>) -> i32 {
    v[a]
}

My question is: why v[a] is i32 but &i32? Because i32 ...have a known size at compile time are stored entirely on the stack, so copies of the actual values are quick to make? (from here)

It looks like Rust have hidden rule to convert type in this situation?

ccQpein
  • 705
  • 7
  • 20
  • 2
    Side note: [it is discouraged to accept `&Vec<_>` and the like as a function argument](https://stackoverflow.com/q/40006219/1233251). – E_net4 Feb 22 '18 at 16:36

1 Answers1

9

There was a small misguidance here. Although the method prototype for Index<Idx> is fn index(&self, index: Idx) -> &T, the syntactical operator x[i] does dereference the output from that &T:

container[index] is actually syntactic sugar for *container.index(index) [...]. This allows nice things such as let value = v[index] if the type of value implements Copy.

So there you go. Your function is indeed returning a copy of the value from the vector, but not from an implicit conversion. If the original intent was to really retrieve a reference to that value, you would do &x[i].

See also:

E_net4
  • 27,810
  • 13
  • 101
  • 139
  • Thank you. It is interesting to learn rust. – ccQpein Feb 22 '18 at 17:37
  • Also worth mentioning that this allows `&x[i]` to reference the value in the vector, since otherwise it'd have to move the value out of the vector, and then take a reference to the moved value which would be unworkable. – loganfsmyth Feb 22 '18 at 19:14
  • 1
    @ccQpein: To be honest, this is a dirty hack really. The problem is that you would really like to be able to parameterize the `Output` associated type of `Index` by a lifetime, allowing the user to decide whether to return a reference or not, but this is not yet possible. Therefore, for ergonomics reasons, we have this weird hack in place. As you may have guessed, I am not a fan :x – Matthieu M. Feb 23 '18 at 16:45
  • @MatthieuM. I suppose you meant to ping @loganfsmyth? – E_net4 Feb 23 '18 at 16:58
  • @E_net4: No, I meant to ping the OP :) I don't find this hack "interesting", it's a wart to me. – Matthieu M. Feb 23 '18 at 17:06