Ownership: differences between tuples and arrays in Rust

Tuples are like anonymous structs, and accessing an element in a tuple behaves like accessing a struct field.

Structs can be partially borrowed (and also partially moved), so &mut out2.a.0.in_a borrows only the first field of the tuple.

The same does not apply to indexing. The indexing operator can be overloaded by implementing Index and IndexMut, so &mut out1.a[0].in_a is equivalent to &mut out1.a.index_mut(0).in_a. While a.0 just accesses a field, a[0] calls a function! Functions can't partially borrow something, so the indexing operator must borrow the entire array.


That is indeed an interesting case. For the second case it works because compiler understands that different part of the structure is borrowed (there's a section in nomicon for that). For the first case compiler is, unfortunately is not that smart (indexing is generally performed by a runtime calculated value), so you need to destruct it manually:

let [mut x, y] = out1.a;
test_ownership(&mut x.in_a, &y);

Tags:

Rust