You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rust函数返回值元组时出现类型不匹配错误

Rust函数返回值类型不匹配问题解决

你的函数代码:

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的类型是BTreeSet<&(u8, u8)>(存储元组的引用),但函数签名要求返回BTreeSet<(u8, u8)>(存储拥有所有权的元组)。由于(u8, u8)实现了Copy trait,只需在插入时解引用元素即可复制出拥有所有权的元组:

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();
    // 解引用&(u8,u8)得到(u8,u8),利用Copy特性复制元素
    for n in &two_byte_vec {
        two_byte_set.insert(*n);
    }

    (two_byte_vec, 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 two_byte_set = two_byte_vec.iter().copied().collect();

    (two_byte_vec, two_byte_set)
}

这里iter()生成引用迭代器,copied()会自动将&(u8,u8)转换为(u8,u8)(因为类型实现了Copy),最后直接collect成BTreeSet<(u8, u8)>。

内容的提问来源于stack exchange,提问作者Abe Hoffman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 01:00:48