【问题标题】:Rust private function throws error when trying to return tuple of valuesRust 私有函数在尝试返回值元组时抛出错误
【发布时间】:2023-01-14 03:10:49
【问题描述】:

我有一个函数,我试图从以下位置返回值的元组:

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

生成此错误:

   |
   |     return (two_byte_vec, two_byte_set);
   |                           ^^^^^^^^^^^^ expected tuple, found `&(u8, u8)`
   |
   = note: expected struct `BTreeSet<(u8, u8)>`
              found struct `BTreeSet<&(u8, u8)>`

显然我不想返回 &amp;two_byte_set - 我想将所有权转移出函数。如何让这两个变量正确返回?

【问题讨论】:

  • 此处的错误消息具有误导性。它在谈论 BTreeMap 持有的类型。即 &(u8, u8)。在插入映射之前取消引用 n 并从 two_byte_set 中删除类型注释
  • @IvanC 错误不是误导,只是被截断了,这就是为什么您应该始终提供完整的错误消息,而不仅仅是其中的一行。

标签: rust tuples return ownership borrow


【解决方案1】:

由于您在for 循环中借用向量进行迭代,因此该循环中n 的类型是&amp;(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());
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-10
    • 2022-11-11
    • 2019-12-02
    • 2017-11-25
    • 1970-01-01
    • 2020-12-15
    • 1970-01-01
    • 2020-07-31
    相关资源
    最近更新 更多