在Rust中修剪一组输入的行

此Rust程序从用户那里收集单词/行,并将每个单词/行添加到变量line_set中。我想在将每个单词添加到line_set之前将代码更改为 trim

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的{​​{1}}开关,它表示“发生此错误是因为某个值仍在借用时被丢弃了”。我曾希望使用--explain方法可以避免该问题。如何克服错误?

lzdfkwdz 回答:在Rust中修剪一组输入的行

str::trim仅产生一个切片,而不产生另一个String,因此当您在其上调用clone时,您正在调用&str的{​​{1}的实现},仅复制Clone(便宜的指针副本)。相反,您应该使用methods之一将&str变成&str,例如Stringto_string或更详细地讲,{{1} }。

to_owned

(playground)

本文链接:https://www.f2er.com/2489858.html

大家都在问