我在从 中返回的迭代器中std::str::SplitWhitespace,需要第一个元素和所有元素的向量。
我尝试使用窥视。然而,这似乎需要一个可变的(我不知道为什么),并且我最终遇到了借用错误。
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
}
}
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
如果我取消注释这两个println,并注释错误的。然后就可以了。let first = first.clone();这导致我在 s之前添加一个克隆println。这解决了它,但我想知道是否有更好的方法。
实现此目的的最简单方法是收集向量,然后获取第一个元素:
let tokens: Vec<_> = line.split_whitespace().collect();
if let Some(first) = tokens.first() {
println!("{first}\n{tokens:?}");
}
Run Code Online (Sandbox Code Playgroud)
请注意 will 的类型tokens是Vec<&str>- 借用自 的字符串切片向量line。如果您想要一个拥有字符串的向量 ( Vec<String>),那么您需要将每个元素映射到一个拥有的字符串:
let tokens: Vec<_> = line.split_whitespace().map(|s| s.to_owned()).collect();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4971 次 |
| 最近记录: |