我正在编写一段Rust程序来收集每个输入行的第一个单词,这有些类似于Unix实用程序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);
}
这让我
$ 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.
我已经阅读了「因为同时以不可变方式借用,所以无法作为可变引用进行借用」,但仍然感到困惑: 可变借用发生在第10行,而不可变借用发生在第12行,那么如何出现「一个已经以不可变方式借用的变量被作为可变引用进行了借用」?至少错误应该是「一个已经以可变方式(在第10行)借用的变量被作为不可变方式(在第12行)进行了借用」。
words.push(word.clone());
没有解决“生命周期问题”呢?因为我正在创建新对象并将它们推入words
中,所以不应该存在任何无效引用的机会 :/ - nalzokword.clone
仍然指向input
,而在下一次迭代中它被更改(因此指向它是指向过时的数据)吗? - phimuemue