将多维数组转换为切片。

huangapple go评论63阅读模式
英文:

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)
    }
}

playground链接

是否有一种非unsafe的快速执行此转换的方法?

英文:

In Rust, I have a square, multidimensional array with a const generic size:

fn generate_array&lt;const N: usize&gt;() -&gt; [[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: &amp;[u32]);

My array doesn't coerce to &amp;[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&lt;const N: usize, T&gt;(arr: &amp;[[T; N]; N]) -&gt; &amp;[T] {
    unsafe {
        std::slice::from_raw_parts(arr.as_ptr() as *const _, N * N)
    }
}

(playground link)

Is there a non-unsafe way to quickly perform this conversion?

答案1

得分: 1

在 Nightly 版本中,存在 &lt;[T]&gt;::flatten()

在稳定版中,标准库中没有相关内容,但有一些 crates,例如 slice-of-array

总之,您的代码是正确的。

英文:

On nightly, there is &lt;[T]&gt;::flatten().

On stable, there is nothing in the standard library, although there is crates [e.g. slice-of-array).

Anyhow, your code is sound.

huangapple
  • 本文由 发表于 2023年6月29日 01:34:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/76575505.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定