gpt4 book ai didi

string - 无法使用 if 表达式附加到字符串而不是 if 语句

转载 作者:行者123 更新时间:2023-11-29 08:02:21 24 4
gpt4 key购买 nike

我有以下工作正常的代码:

fn main() {
let mut example = String::new();

if 1 + 1 == 2 {
example += &"string".to_string()
} else {
example += &'c'.to_string()
};

println!("{}", example);
}

当我将代码更改为:

fn main() {
let mut example = String::new();

example += if 1 + 1 == 2 {
&"string".to_string()
} else {
&'c'.to_string()
};

println!("{}", example);
}

我收到以下错误:

error[E0597]: borrowed value does not live long enough
--> src/main.rs:5:10
|
5 | &"string".to_string()
| ^^^^^^^^^^^^^^^^^^^^ temporary value does not live long enough
6 | } else {
| - temporary value dropped here while still borrowed
7 | &'c'.to_string()
8 | };
| - temporary value needs to live until here

error[E0597]: borrowed value does not live long enough
--> src/main.rs:7:10
|
7 | &'c'.to_string()
| ^^^^^^^^^^^^^^^ temporary value does not live long enough
8 | };
| - temporary value dropped here while still borrowed
|
= note: values in a scope are dropped in the opposite order they are created

这对我来说毫无意义,因为这两个片段看起来完全相同。为什么第二个代码段不起作用?

最佳答案

你已经 already seen an explanation as to why this code cannot be compiled .下面是一些有效的代码,并且更接近您的目标:

example += &if 1 + 1 == 2 {
"string".to_string()
} else {
'c'.to_string()
};

我不会声称这是惯用的 Rust。让我印象深刻的一件事是将 "string" 不必要地分配到 String 中。我会使用 String::push_str 编写这段代码和 String::push :

if 1 + 1 == 2 {
example.push_str("string");
} else {
example.push('c');
}

如果您不附加字符串,我会直接对其求值:

let example = if 1 + 1 == 2 {
"string".to_string()
} else {
'c'.to_string()
};

我什至可以使用动态调度(尽管不太可能):

let s: &std::fmt::Display = if 1 + 1 == 2 { &"string" } else { &'c' };
let example = s.to_string();

use std::fmt::Write;
let mut example = String::new();
let s: &std::fmt::Display = if 1 + 1 == 2 { &"string" } else { &'c' };
write!(&mut example, "{}", s).unwrap();

另见:

关于string - 无法使用 if 表达式附加到字符串而不是 if 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53071283/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com