我有一个未知大小的数组,我想获得该数组的一部分并将其转换为静态大小的数组:
fn pop(barry: &[u8]) -> [u8; 3] {
barry[0..3] // mismatched types: expected `[u8, ..3]` but found `&[u8]`
}
Run Code Online (Sandbox Code Playgroud)
我该怎么做?
我想在编译时检查实现中使用的切片是否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)