Help me understand why `std::array::map` moves instead of references?
⚓ Rust 📅 2026-01-30 👤 surdeus 👁️ 13I'm trying to understand why the map method on a Rust array moves (or copies) itself? For example this seems like idiomatic code in every other language I'm familiar with:
struct Thing { n: i32 }
let arr = [Thing { n: 1 }, Thing { n: 2 }, Thing { n: 3 }, ];
let _arr_x2 = arr.map(|d| d.n * 2 );
let _arr_x4 = arr.map(|d| d.n * 4 ); // NOPE: `arr` already moved! (unless Thing is Copy…]
But it fails in Rust because the first map consumes the original array! I eventually did find .each_ref() which helps in my original circumstance where I don't want to copy the elements themselves either. Seems weird that I have to make an extra intermediate array just to get the final one, but maybe this is something I can just assume probably/sometimes/maybe/perhaps gets optimized away?
But I just feel like yet another thing about my mental model of Rust must be broken to get tripped up like this. Why doesn't .map iterate over immutable refs of the items in the first place?
7 posts - 6 participants
🏷️ Rust_feed