Reputation: 751
Use for
loop on a rust array works correctly:
fn main() {
let v = [1, 2, 3, 4, 5];
for _ in v.into_iter() {}
for _ in v.into_iter() {}
}
But substituting a vec doesn't compile:
fn main() {
let v = vec![1, 2, 3, 4, 5];
for _ in v.into_iter() {}
for _ in v.into_iter() {}
}
The error:
use of moved value: `v`
I understand why this program does not work with vec. But why does it work with array? I was expecting a similar error in the array example, but it gives no error.
Upvotes: 3
Views: 899
Reputation: 1503
Added detail:
Arrays are stored on the stack in Rust (like C/C++), therefore, they can be moved -- Copy() in rust -- which makes a deep copy of the data, but it's ok because stack data is supposed to be light-weight.
Vectors are stored on the heap in Rust (like C/C++), therefore, they usually CANNOT be moved, and must usually be deep copied.
Here is a great explanation on the difference between Copy() and Clone()
Original Response:
As another commenter mentioned, Arrays in Rust implement the Copy
trait, and can therefore be passed-by-value multiple times, whereas Vector types must be explicitly clone()
d to achieve the same behavior.
In Rust, when a function's parameter is pass-by-value, the compiler defaults to doing a move of a copy on all calls except the last one, on the last call it will transfer ownership of the original, instead of a copy/clone. The compiler will not automatically run clone()
, if Copy
isn't implemented.
Here is the doc for Copy
trait: https://doc.rust-lang.org/std/marker/trait.Copy.html
Array's impl of Copy
documentation can be found here: https://doc.rust-lang.org/std/primitive.array.html#impl-Copy-for-%5BT%3B%20N%5D
Here is a great article with more details: https://colinsblog.net/2021-04-16-rust-ownership-comparisons/
Upvotes: 4