相关疑难解决方法(0)

如何在Rust中将切片作为数组?

我有一个未知大小的数组,我想获得该数组的一部分并将其转换为静态大小的数组:

fn pop(barry: &[u8]) -> [u8; 3] {
    barry[0..3] // mismatched types: expected `[u8, ..3]` but found `&[u8]`
}
Run Code Online (Sandbox Code Playgroud)

我该怎么做?

arrays rust

36
推荐指数
5
解决办法
2万
查看次数

如何在编译时检查切片是否具有特定大小?

我想在编译时检查实现中使用的切片是否From具有特定大小。

游乐场

#[derive(Debug)]
struct Pixel {
    r: u8,
    g: u8,
    b: u8,
}

impl From<&[u8]> for Pixel {
    fn from(arr: &[u8]) -> Pixel {
        Pixel {
            r: arr[0],
            g: arr[1],
            b: arr[2],
        }
    }
}

fn main() {
    println!("Hello, world!");

    let arr: [u8; 9] = [1, 2, 3, 4, 5, 6, 7, 8, 9];
    let pixels: Vec<Pixel> = arr.chunks_exact(3).map(Pixel::from).collect();
    println!("{:.?}", pixels);
}
Run Code Online (Sandbox Code Playgroud)

这并不像我想要的那么具体。我想尽可能清楚地检查arr传递给is 3 个元素(在编译时)。Pixel::from<&[u8]>()

想到了assert!(arr.len()==3),但这在运行时检查。

所以我想也许我可以通过( Playground )进行转换:

impl From<[u8; …
Run Code Online (Sandbox Code Playgroud)

rust

2
推荐指数
1
解决办法
690
查看次数

标签 统计

rust ×2

arrays ×1