如何获得一个切片作为防锈静态数组? [英] How to get a slice as a static array in rust?
本文介绍了如何获得一个切片作为防锈静态数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我不知道如果我使用的是正确的术语锈,所以随时纠正我在此。
I don't know if I'm using the correct Rust terminology, so feel free to correct me on this.
我有一个未知大小的数组,我想获得该数组的一个切片,将其转换为静态大小的数组:
I have an array of an unknown size, and I would like to get a slice of that array and convert it to a statically sized array:
fn pop(barry: &[u8]) -> [u8, ..3] {
barry.slice(0, 3); // mismatched types: expected `[u8, ..3]` but found `&[u8]`
}
我会怎么做呢?
How would I do this?
推荐答案
下面是一个你要求的类型特征匹配功能。
Here's a function that matches the type signature you asked for.
fn pop(barry: &[u8]) -> [u8, ..3] {
[barry[0], barry[1], barry[2]]
}
不过,由于巴里
可以有少于三个元素,你可能要返回一个选项< U8,..三合一>
而非 [U8,..三合一]
。
But since barry
could have fewer than three elements, you may want to return an Option<[u8, ..3]>
rather than a [u8, ..3]
.
fn pop(barry: &[u8]) -> Option<[u8, ..3]> {
if barry.len() < 3 {
None
} else {
Some([barry[0], barry[1], barry[2]])
}
}
这篇关于如何获得一个切片作为防锈静态数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文