rust 安全地将1D切片转换为2D切片

4sup72z8  于 2022-11-12  发布在  其他
关注(0)|答案(1)|浏览(162)

我想将1D切片[f64]转换为2D切片[[f64; 2],即[x0, y0, x1, y1, ...]-〉[[x0, y0], [x1, y1], ...]
我目前的解决方案使用不安全的程式码:

let points1d: &[f64] = &[0.0, 1.0, 2.0, 3.0];
if points1d.len() % 2 != 0 {
   panic!("Bad slice");
}
let points2d: &[[f64; 2]] = unsafe { std::mem::transmute::<&[f64], &[[f64; 2]]>(points1d) };

我试着搜索,但是没有找到我的关键字(改变数组的维数/间距,重新解释转换,转换切片)。

6l7fqoea

6l7fqoea1#

最好的方法是使用bytemuck crate。这同样有效(它在引擎盖下使用相同的代码)。

let points1d: &[f64] = &[0.0, 1.0, 2.0, 3.0];
let points2d: &[[f64; 2]] = bytemuck::cast_slice(points1d);

相关问题