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

标签 string rust borrow-checker borrowing

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

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/

相关文章:

Java:防止编码字符串的自动解码

android - java.lang.UnsatisfiedLinkError : No implementation found (NDK, Kotlin) - 已修复

rust - 如何在 Rust 中使用自由类型绑定(bind)?

error-handling - Rust Arc/Mutex Try 宏借用的内容

rust - 我可以在 Rust 中将不可变借用标记为独占吗?

javascript - 在字符串开头匹配子字符串的最佳方法(有一些限制)

java - 如何在算术方程中使用字符串值?

rust - 为什么使用外部包装箱的功能需要将依赖特征纳入范围?

rust - Rustfmt 是否可以选择使类型显式化?

rust - 为什么多个可变引用使无法将结构的成员分配给自身? [复制]