50.7.1Two ways of accessing a value by index¶
The String struct allocates memory on the heap and thus does not
implement the Copy trait. As a consequence, indexing the vector
(v[0]) results in a tentative to move the value.
The compiler suggests us two solutions:
Either borrow the indexed value (
&v[0]).Or clone it (
v[0].clone()).
let mut v: Vec<String> = Vec::new();
v.push(String::from("abc"));
let a = v[0];
a[E0507] Error: cannot move out of index of `Vec<String>`
╭─[ command_2:1:1 ]
│
3 │ let a = v[0];
│ ┬─┬─│
│ ╰───── help: consider borrowing here: `&`
│ │ │
│ ╰─── move occurs because value has type `String`, which does not implement the `Copy` trait
│ │
│ ╰─ help: consider cloning the value if the performance cost is acceptable: `.clone()`
───╯