Rust 在使用 push_str() 将一个新字符串连接到另一个字符串时是否会在这个衬里给出错误?

use*_*749 0 string concatenation rust

我想连接一个字符串。
在我看来,以下代码应该给出某种恐慌或编译器错误。

let mut s = String::from("abc").push_str("x");
println!("{:?}", s); // Prints ()
Run Code Online (Sandbox Code Playgroud)

但这段代码有效:

let mut s = String::from("abc");
s.push_str("x");  
println!("{:?}", s); // Prints "abcx"
Run Code Online (Sandbox Code Playgroud)

Joh*_*ica 5

push_str不返回输入字符串;它没有返回值。没有返回值的方法隐式返回()

pub fn push_str(&mut self, string: &str)
Run Code Online (Sandbox Code Playgroud)

  • 确实如此。这就是代码编译的原因。不过,临时字符串在 `let` 语句的末尾被删除,因为 `push_str` 不返回它。 (2认同)

hel*_*low 5

在我看来,以下代码应该给出某种恐慌或编译器错误。

为什么应该这样?这段代码是完全合法的。

s现在是一个单位值(),因为您正在使用{:?}Debug打印的输出()

现在正是向您介绍clippy的好时机。您会cargo clippy收到以下警告:

warning: this let-binding has unit value
 --> src/main.rs:2:5
  |
2 |     let mut s = String::from("abc").push_str("x");
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: omit the `let` binding: `String::from("abc").push_str("x");`
  |
  = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#let_unit_value
  = note: `#[warn(clippy::let_unit_value)]` on by default
Run Code Online (Sandbox Code Playgroud)

这表明您的代码中有问题。