0

The following does not compile. What's the canonical way to make this work?

let file = File::open(&args.path)?;
let reader = BufReader::new(file);

for line in reader.lines() {
    if line?.contains(&args.pattern) {
        println!("{}", line?);
    }
}

Here's the error message, for completeness:

34 |      println!("{}", line?);
   |                     ^^^^ value used here after move
MeetTitan
  • 3,383
  • 1
  • 13
  • 26
CXJ
  • 4,301
  • 3
  • 32
  • 62

1 Answers1

5

In your example line is a Result, which is moved when you use ? (but do we really need the Result after you've unwrapped its contents???). To alleviate your problem, let's shadow the value of the Result in a local variable of the same name.

for line in reader.lines() {
    let line = line?;
    if line.contains(&args.pattern) {
        println!("{}", line);
    }
}
MeetTitan
  • 3,383
  • 1
  • 13
  • 26
  • Thanks. This was my initial solution, too. But as a developer coming from numerous other languages without Rust's ownership model, creating an extra local variable just felt wrong somehow. – CXJ Jun 21 '20 at 23:04
  • 1
    I understand, it seems clunky at first. I believe (but am not positive) that when we shadow a variable by using the same name the previous value is dropped from memory, so it's not even incurring a performance hit; we're just making the borrow checker happy :) – MeetTitan Jun 21 '20 at 23:43