首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >借款时临时价值下降-锈病

借款时临时价值下降-锈病
EN

Stack Overflow用户
提问于 2022-08-30 03:20:37
回答 1查看 181关注 0票数 1

我试图通过字节迭代器遍历字符串。我的目的是将每个字节转换成一个单字母的&str,以匹配模式。基于匹配臂,它将尝试将该值添加到向量中。然而,我得到了一个错误,这是阻止程序编译。错误消息如下:

代码语言:javascript
运行
复制
Line 15, Char 22: temporary value dropped while borrowed (solution.rs)
   |
15 |             let b = &[byte];
   |                      ^^^^^^ creates a temporary which is freed while still in use
...
20 |                     stack.push(c);
   |                     ------------- borrow later used here
...
39 |         }
   |         - temporary value is freed at the end of this statement
   |
   = note: consider using a `let` binding to create a longer lived value
For more information about this error, try `rustc --explain E0716`.
error: could not compile `prog` due to previous error

作为参考,这是底层代码:

代码语言:javascript
运行
复制
let mut stack: Vec<&str> = Vec::new();

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

Stack Overflow用户

回答已采纳

发布于 2022-08-30 03:53:57

问题是您创建了一个临时数组[byte],并尝试将其借用到Vec中。但是数组只存在到作用域的末尾,而Vec的寿命更长!

通常的解决方案是堆-分配&strstack.push(c.to_owned())。但是,因为一个元素数组的内存布局与元素的内存布局匹配,所以您可以不需要分配。首先,您需要获得与原始&str具有相同生存期的字节的引用,而不是按值字节。这可以通过迭代s.as_bytes() (返回&[u8])而不是s.bytes() (返回impl Iterator<Item = u8>)来实现。

其次,您需要将此字节转换为具有相同生存期的数组。标准库中有一个函数可以这样做:std::array::from_ref()

所以:

代码语言:javascript
运行
复制
let mut stack: Vec<&str> = Vec::new();

for byte in s.as_bytes() {
    let b = std::array::from_ref(byte);
    let c = str::from_utf8(b).unwrap();

    match c {
        "a" | "b" => {
            stack.push(c);
        }
        _ => println!("not a or b"),
    }
}
票数 1
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73536781

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档