I agree, this is a bit confusing. So let's first see why this is not allowed by the Rust compiler.
Why is it not allowed
The index operator [] is something that can be overloaded, which means that language users can specify how it works. Rust tries to minimize the number of types in which the compiler has specialized knowledge. As a result, and despite its popularity, Vec<T> is a common type defined by the library. You can write your own Vec<T> without telling the compiler about it!
Vec<T> also overloads the index operator, allowing you to index the vector. But since overloading could do something, it could always return the first element of a vector! And if you assume that the index operator would do such a strange thing, this code should not be allowed:
my_vec[0].change_value(my_vec[1].value.as_str());
Because my_vec[0] and my_vec[1] refer to the same value.
How to make it work
Of course, the index operator is not implemented in such a stupid way, and we know that. To get two references to different elements of the vector (where at least one is changed), we must use some special functions instead of the index operator. And there are several ways to do this:
I canβt tell you which method to use because I donβt know your specific use case. But to fix your example, you can write:
let (head, tail) = my_vec.split_first_mut(); head.change_value(tail[0].value.as_str());
source share