Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

About trait Index implement of Vector in Rust [duplicate]

Tags:

rust

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?

like image 653
ccQpein Avatar asked Dec 06 '25 04:12

ccQpein


1 Answers

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:

  • Meaning of the ampersand '&' and star '*' symbols in Rust
  • Does Rust automatically dereference primitive type references?
like image 51
E_net4 stands with Ukraine Avatar answered Dec 07 '25 23:12

E_net4 stands with Ukraine



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!