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)
push_str不返回输入字符串;它没有返回值。没有返回值的方法隐式返回()。
pub fn push_str(&mut self, string: &str)
Run Code Online (Sandbox Code Playgroud)
在我看来,以下代码应该给出某种恐慌或编译器错误。
为什么应该这样?这段代码是完全合法的。
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)
这表明您的代码中有问题。
| 归档时间: |
|
| 查看次数: |
122 次 |
| 最近记录: |