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

Rust编译错误:Temporary value dropped while borrowed 求解

Rust编译错误分析与解决

错误根源

你这段代码的核心问题是悬垂引用:

  • &[byte]创建的是一个临时数组,它的生命周期只限于当前循环迭代的语句块内。
  • str::from_utf8(b)返回的&str引用,指向的就是这个临时数组。
  • 当循环迭代结束,临时数组会被自动销毁,但你把这个引用存入了Vec<&str>,导致Vec里的引用指向已经被释放的内存——Rust的所有权系统会直接阻止这种不安全行为,所以抛出了temporary value dropped while borrowed错误。

实用解决方案

方案1:直接匹配字节(最简洁高效)

既然是遍历bytes()迭代器,直接匹配字节值b'a'和b'b'即可,完全不需要转成&str:

let mut stack: Vec<char> = Vec::new(); // 若只需存储字节,可改为Vec<u8>

for byte in s.bytes() {
    match byte {
        b'a' | b'b' => stack.push(byte as char),
        _ => println!("not a or b"),
    }
}

方案2:存储拥有所有权的String

如果业务逻辑必须涉及字符串操作,把Vec的类型改为Vec<String>,存储拥有所有权的字符串,避免引用生命周期问题:

let mut stack: Vec<String> = Vec::new();

for byte in s.bytes() {
    let byte_arr = [byte];
    let c = str::from_utf8(&byte_arr).unwrap().to_string();
            
    match c.as_str() {
        "a" | "b" => stack.push(c),
        _ => println!("not a or b"),
    }
}

方案3:使用静态字符串字面量

因为"a"和"b"是静态字符串(生命周期为'static),可以直接匹配后存入Vec<&'static str>:

let mut stack: Vec<&'static str> = Vec::new();

for byte in s.bytes() {
    match byte {
        b'a' => stack.push("a"),
        b'b' => stack.push("b"),
        _ => println!("not a or b"),
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 14:21:39