我试图通过字节迭代器遍历字符串。我的目的是将每个字节转换成一个单字母的&str,以匹配模式。基于匹配臂,它将尝试将该值添加到向量中。然而,我得到了一个错误,这是阻止程序编译。错误消息如下:
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作为参考,这是底层代码:
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"),
}
}发布于 2022-08-30 03:53:57
问题是您创建了一个临时数组[byte],并尝试将其借用到Vec中。但是数组只存在到作用域的末尾,而Vec的寿命更长!
通常的解决方案是堆-分配&str:stack.push(c.to_owned())。但是,因为一个元素数组的内存布局与元素的内存布局匹配,所以您可以不需要分配。首先,您需要获得与原始&str具有相同生存期的字节的引用,而不是按值字节。这可以通过迭代s.as_bytes() (返回&[u8])而不是s.bytes() (返回impl Iterator<Item = u8>)来实现。
其次,您需要将此字节转换为具有相同生存期的数组。标准库中有一个函数可以这样做:std::array::from_ref()。
所以:
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"),
}
}https://stackoverflow.com/questions/73536781
复制相似问题