<分区>
我希望将使用 format!
宏创建的 String
转换为 &str
并使用 将其分配给一个值让
绑定(bind):
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);
}
( Rust Playground )
当我这样做时,编译器提示临时 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
绑定(bind)中:
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);
}
但这似乎并没有解决问题,因为当我在此绑定(bind)上调用 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
时有效,但我宁愿不这样做,因为这会给原始代码库带来很多麻烦。
此外,这看起来确实像是一种逃避,因为那时我仍然不知道为什么会失败。
我将如何系统地解决这个问题?