我有一个函数,我试图从返回值的元组:
fn get_two_bytes(data: &[u8]) -> (Vec<(u8, u8)>, BTreeSet<(u8, u8)>) {
let two_byte_vec = data
.chunks(2)
.map(|x| (x[0], x[1]))
.collect::<Vec<_>>();
let mut two_byte_set : BTreeSet<&(u8, u8)> = BTreeSet::new();
for n in &two_byte_vec {
two_byte_set.insert(n);
}
return (two_byte_vec, two_byte_set);
}
这个错误产生:
error[E0308]: mismatched types
--> src/lib.rs:13:27
|
13 | return (two_byte_vec, two_byte_set);
| ^^^^^^^^^^^^ expected tuple, found `&(u8, u8)`
|
= note: expected struct `BTreeSet<(u8, u8)>`
found struct `BTreeSet<&(u8, u8)>`
我显然不想返回&two_byte_set
-我想将所有权转移到函数之外。如何使这两个变量正确返回?
这里的错误信息是误导。
这里讨论的是BTreeMap
所持有的类型,也就是&(u8, u8)
而不是你在函数签名中承诺的(u8, u8)
。因为u8
是Copy
,所以元组(u8, u8)
也是Copy
,这意味着您可以在插入映射之前删除n
,并从two_byte_set
中删除类型注释。
use std::collections::BTreeSet;
fn get_two_bytes(data: &[u8]) -> (Vec<(u8, u8)>, BTreeSet<(u8, u8)>) {
let two_byte_vec = data.chunks(2).map(|x| (x[0], x[1])).collect::<Vec<_>>();
let mut two_byte_set = BTreeSet::new();
for &n in &two_byte_vec {
two_byte_set.insert(n);
}
(two_byte_vec, two_byte_set);
}
由于您在for
循环中借用vector进行迭代,因此该循环中n
的类型为&(u8, u8)
。幸运的是,可以克隆u8
的元组,因此只需将它们克隆到您的集合中。
let mut two_byte_set : BTreeSet<(u8, u8)> = BTreeSet::new();
for n in &two_byte_vec {
two_byte_set.insert(n.to_owned());
}