在 Rust 中修剪一组输入行

Trimming lines of input for a set in Rust

此 Rust 程序从用户那里收集 words/lines,并将每个添加到变量 line_set。我想将代码更改为每个单词 trim,然后再将其添加到 line_set

use std::collections::HashSet;
use std::io;

fn main() {
  let mut line_set = HashSet::new();

  for i in 1..4 {
    let mut line = String::new();
    io::stdin()
      .read_line(&mut line)
      .expect("Failed to read line");
    //let line = line.trim();
    line_set.insert(line.clone());
    if i == 3 {
      for l in &line_set {
        println!("{}", l);
      }
    }
  }
}

当我尝试添加对 String::trim 的调用时,应用到当前单词,程序不再编译:

error[E0597]: `line` does not live long enough
  --> src/main.rs:12:20
   |
12 |         let line = line.trim();
   |                    ^^^^ borrowed value does not live long enough
13 |         line_set.insert(line.clone());
   |         -------- borrow later used here
...
19 |     }
   |     - `line` dropped here while still borrowed

我用了rustc--explain开关,它与"This error occurs because a value was dropped while it was still borrowed"有关。我曾希望使用 clone 方法可以避免该问题。我如何克服错误?

str::trim just produces a slice, not another String, so when you call clone on it, you're calling &str's implementation of Clone, which just copies the &str (a cheap pointer copy). Instead, you should use one of the methods&str 变成 String,例如 to_stringto_owned 或更详细的 String::from

use std::collections::HashSet;
use std::io;

fn main() {
    let mut line_set = HashSet::new();

    for i in 1..4 {
        let mut line = String::new();
        io::stdin()
            .read_line(&mut line)
            .expect("Failed to read line");
        line_set.insert(line.trim().to_owned());
        if i == 3 {
            for l in &line_set {
                println!("{}", l);
            }
        }
    }
}

(playground)