我希望将使用 format!
宏创建的 String
转换为 &str
,并使用 let
绑定将其赋值给一个变量:
fn main() {
let my_bool = true;
let other = String::from("my_string");
let result = if my_bool {
format!("_{}", other).as_str()
} else {
"other"
};
println!("{}", result);
}
当我这样做时,编译器会抱怨临时的 String
值在语句结束时被释放(从我的理解来看),这意味着我无法动态创建 &str
:
error[E0716]: temporary value dropped while borrowed
--> src/main.rs:5:9
|
4 | let result = if my_bool {
| ------ borrow later stored here
5 | format!("_{}", other).as_str()
| ^^^^^^^^^^^^^^^^^^^^^ creates a temporary which is freed while still in use
6 | } else {
| - temporary value is freed at the end of this statement
|
我一直在努力理解Rust的生命周期系统,但我真的无法理解其中的某些内容。Rust建议以下:
= note: consider using a `let` binding to create a longer lived value
我将 format!("_{}", other)
包裹在一个 let
绑定中:
fn main() {
let my_bool = true;
let other = String::from("my_string");
let result = if my_bool {
let s = format!("_{}", other);
s.as_str()
} else {
"other"
};
println!("{}", result);
}
但是它似乎不能解决问题,因为当我对此绑定调用as_str()
时,它仍然抱怨借用的值没有足够长的生命周期:
error[E0597]: `s` does not live long enough
--> src/main.rs:6:9
|
4 | let result = if my_bool {
| ------ borrow later stored here
5 | let s = format!("_{}", other);
6 | s.as_str()
| ^ borrowed value does not live long enough
7 | } else {
| - `s` dropped here while still borrowed
当我省略整个if
语句时,它可以正常工作,但我不想这样做,因为这将在原始代码库中引起很多麻烦。
此外,这似乎有点像逃避责任,因为那样我仍然不知道为什么会失败。
我该如何系统地解决这个问题?
str
?如果你将其转换为str
,那么谁负责拥有该内存呢?https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=c7d3b896cb0865e70f0ce501492de439 运行得很好。 - loganfsmythstr
的原因是它是匹配语句的一部分,该语句返回str
,在这种情况下,我希望可以返回str
而不必在每个匹配 case 中都使用String::from(...)
来进行包装。 - Joël Abrahams&str
是一个借用值,因此为了返回一个&str
,被借用的内存需要存在某个地方。如果你的match
必须返回一个&str
,那么你显式地限制自己只能返回在match
运行之前已经存在的借用值,这意味着你不能在其中创建一个新的String
。 - loganfsmyth