Why does `name = *name.trim();` give me `expected

2019-07-15 15:09发布

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`

标签: rust
1条回答
够拽才男人
2楼-- · 2019-07-15 15:38

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().

查看更多
登录 后发表回答