fn main(){
let nums = ["aaa".to_string(), "bbb".to_string(), "ccc".to_string(),
"ddd".to_string(), "eee".to_string()];
let num1 = nums[0];
println!("{}", num1);
}
The compiler complained :
consider borrowing here: &rustcE0508
main.rs(71, 16): original diagnostic
cannot move out of type [String; 5], a non-copy array
cannot move out of hererustc[Click for full compiler diagnostic](rust-analyzer-diagnostics-view:/diagnostic message [0]?0#file:///c%3A/Users/bingru/work/rust/my_project/src/main.rs)
why rust would not allow moving the ownership of nums[0] to num2??
Because an array cannot be left in a partially initialized state, so you cannot move out one element while the rest is left in place.
To move all elements, consider e. g. converting to an iterator. To move one element without leaving the array partially uninitiated (which works by also moving a different value back into the array at the same time), consider using helper functions like std::mem::replace or std::mem::take.
Array can't have a "hole" that is missing an element.
This is because Rust stores all array elements consecutively inline in the array, without room for extra information whether the element is there or not.
In Rust items can't be null or missing, unless you explicitly allow doing so by wrapping items in an Option.
Part of the reason this isn't allowed it because indexing is a trait operation. So you're technically trying to move from behind a shared reference, and also the compiler can't assume the returned reference refers to any particular place.
The language could conceivably allow this if indexing of arrays with literals or consts was built-in "magic" similar to Box. Then the initialization state of each slot could be tracked statically, like it is for the fields of nominal structs (and Box's allocation slot).
Pattern matching doesn't use indexing and understands arrays enough for this to work:
let nums = ["aaa".to_string(), "bbb".to_string(), "ccc".to_string(),
"ddd".to_string(), "eee".to_string()];
let [ num1, rest @ .. ] = nums;
println!("{num1}");
println!("{rest:?}");
}