Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is an array not moved after the for block like a vector?

I’m new to this language and am currently reading Rust in action. I understand why you’re able to access the vector after a for loop. However, I don’t understand why this works:

let list = [1, 2, 3, 4, 5];
for item in list {
    println!("{}", item);
}
println!("{:#?}", list);

If I try the same with a vector, it doesn’t work without it being a reference inside the for, which I understand why.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Arrays of numbers are never moved. Arrays are Copy if their underlying type is Copy, which means that, like basic numerical types, they’re always copied rather than moved. They’re eligible for this special treatment since an array is just a contiguous chunk of the bytes representing its elements, so if its elements can be copied byte-by-byte, then so can the whole array. A vector, on the other hand, involves dynamic allocation and pointers, so blindly copying the bytes of a vector isn’t safe.

When you use a for loop, you’re invoking into_iter on the type, which takes self by value. For a type that’s not Copy, this requires the target of the for loop to be moved to construct the iterator. But for types that are Copy, Rust makes a copy of the array and then uses that copy in into_iter instead.

As the relevant documentation (linked above) says:

[…] Creates a consuming iterator, that is, one that moves each value out
of the array (from start to end). The array cannot be used after
calling this unless T implements Copy, so the whole array is copied.

emphasis mine

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading