英文:
Cast multidimensional array to slice
问题
在Rust中,我有一个带有const泛型大小的正方形多维数组:
fn generate_array<const N: usize>() -> [[u32; N]; N] {
// ...
}
我想将这个数组传递给一个接受一维数组的库函数:
fn library_function(width: usize, height: usize, data: &[u32]);
我的数组不能强制转换为&[u32]
,因此我不能只传递一个引用。我知道这应该是一个微不足道的转换,但我找不到一个惯用的方法来做到这一点。根据这个帖子,我创建了一个函数来从原始指针构建切片,但我不确定是否有某些类型在这种情况下是无效的。
const fn as_flat_slice<const N: usize, T>(arr: &[[T; N]; N]) -> &[T] {
unsafe {
std::slice::from_raw_parts(arr.as_ptr() as *const _, N * N)
}
}
是否有一种非unsafe
的快速执行此转换的方法?
英文:
In Rust, I have a square, multidimensional array with a const generic size:
fn generate_array<const N: usize>() -> [[u32; N]; N] {
// ...
}
I want to pass this array to a library that takes a one-dimensional array:
fn library_function(width: usize, height: usize, data: &[u32]);
My array doesn't coerce to &[u32]
so I can't just pass a reference. I know this should be a trivial conversion, but I couldn't find an idiomatic way of doing it. From this post, I created a function to construct the slice from a raw pointer, but I am not sure if there are certain types where this is invalid.
const fn as_flat_slice<const N: usize, T>(arr: &[[T; N]; N]) -> &[T] {
unsafe {
std::slice::from_raw_parts(arr.as_ptr() as *const _, N * N)
}
}
Is there a non-unsafe
way to quickly perform this conversion?
答案1
得分: 1
在 Nightly 版本中,存在 <[T]>::flatten()
。
在稳定版中,标准库中没有相关内容,但有一些 crates,例如 slice-of-array
。
总之,您的代码是正确的。
英文:
On nightly, there is <[T]>::flatten()
.
On stable, there is nothing in the standard library, although there is crates [e.g. slice-of-array
).
Anyhow, your code is sound.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论