Consider the example (does not build):
use std::io::{self, Write};
fn main() {
io::stdout().write(b"Please enter your name: ");
io::stdout().flush();
let mut name = String::new();
io::stdin().read_line(&mut name);
name = *name.trim();
println!("Hello, {}!", name);
}
Why do I get the following error?
error[E0308]: mismatched types
--> src/main.rs:8:12
|
8 | name = *name.trim();
| ^^^^^^^^^^^^ expected struct `std::string::String`, found str
|
= note: expected type `std::string::String`
= note: found type `str`
Let's look at the method signature of str::trim():
fn trim(&self) -> &str
It returns a &str and not a String! Why? Because it doesn't need to! Trimming is an operation that doesn't need to allocate a new buffer and thus doesn't result in an owned string. A &str is just a pointer and a length... by incrementing the pointer and reducing the length, we can have another view into the string-slice. That's all what trimming does.
So if you really want to transform the trimmed string into an owned string, say name.trim().to_owned().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With