What I am trying to do
我有从std::str::SplitWhitespace
返回的in迭代器,我需要第一个元素,以及所有元素的一个向量.
What I have tried
我试着用偷窥.然而,这似乎需要一个可变的(我不能我们为什么),我以borrow 错误结束.
Simplified code, with compile errors.
fn main(){
let line = "hello, world";
let mut tokens = line.split_whitespace().peekable();
if let Some(first) = tokens.peek() {
//println!("{first}"); //works
//println!("{tokens:?}"); // works
println!("{first}\n{tokens:?}"); //compile error
}
}
error[E0502]: cannot borrow `tokens` as immutable because it is also borrowed as mutable
--> src/main.rs:7:29
|
4 | if let Some(first) = tokens.peek() {
| ------------- mutable borrow occurs here
...
7 | println!("{first}\n{tokens:?}"); //error
| --------------------^^^^^^-----
| | |
| | immutable borrow occurs here
| mutable borrow later used here
如果我不 comments 这两个println
,而 comments 错误的那个.那它就起作用了.这导致我添加了一个克隆let first = first.clone();
,在println
之前.这解决了它,但我想知道是否有更好的方法.