Is there a way to not have to initialize arrays twice?

≡放荡痞女 提交于 2019-11-27 15:07:46
Dylan

NOTE: This is an old answer, std::mem::uninitialized have been deprecating in 1.38.0: use mem::MaybeUninit instead


In some cases, you can use std::mem::uninitialized:

let mut ys: [i32; 1000] = unsafe { std::mem::uninitialized() };

This is unsafe because accessing uninitialized values is undefined behavior in Rust and the compiler can no longer guarantee that every value of ys will be initialized before it is read. It can also easily cause undefined behavior if the type inside the array (i32 here) is not valid for all possible bit patterns. This means that something like std::mem::uninitialized::<[&i32; 1]>() is immediate undefined behavior, regardless of what you do to the array afterwards.

You cannot collect into an array, but if you had a Vec instead, you could do:

let ys: Vec<_> = xs.iter().map(|&x| x / 3).collect();

For your specific problem, you could also clone the incoming array and then mutate it:

let mut ys = xs.clone();
for y in ys.iter_mut() { *y = *y / 3 }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!