I'm writing a Rust program to collect the first words of each input line, which is somewhat similar to the Unix utility cut
.
use std::io;
fn main() {
let mut words = Vec::new();
let mut input = String::new();
loop {
match io::stdin().read_line(&mut input) {
std::result::Result::Ok(_) => {
let words_line: Vec<&str> = input.split_whitespace().collect();
match words_line.get(0) {
Some(&word) => {
words.push(word.clone());
},
_ => continue,
}
}
std::result::Result::Err(_) => break
}
}
println!("{:?}", words);
}
This gives me
$ cargo run
Compiling foo v0.1.0 (/home/ubuntu/projects/foo)
error[E0502]: cannot borrow `input` as mutable because it is also borrowed as immutable
--> src/main.rs:10:37
|
10 | match io::stdin().read_line(&mut input) {
| ^^^^^^^^^^ mutable borrow occurs here
11 | std::result::Result::Ok(_) => {
12 | let words_line: Vec<&str> = input.split_whitespace().collect();
| ----- immutable borrow occurs here
...
24 | println!("{:?}", words);
| ----- immutable borrow later used here
error: aborting due to previous error
For more information about this error, try `rustc --explain E0502`.
error: could not compile `foo`
To learn more, run the command again with --verbose.
I have read Cannot borrow as mutable because it is also borrowed as immutable but am still confused: the mutable borrow happens on line 10 whereas the immutable one happens on line 12, so how could "a variable already borrowed as immutable was borrowed as mutable" happen? At least the error should be "a variable already borrowed as mutable (on line 10) was borrowed as immutable (on line 12)".