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之前.这解决了它,但我想知道是否有更好的方法.

推荐答案

实现这一点的最简单方法是只收集向量,然后获取第一个元素:

let tokens: Vec<_> = line.split_whitespace().collect();
if let Some(first) = tokens.first() {
    println!("{first}\n{tokens:?}");
}

注意,tokens的类型将是Vec<&str>--从lineborrow 的字符串片的矢量.如果您想要拥有字符串的向量(Vec<String>),则需要将每个元素映射到拥有的字符串:

let tokens: Vec<_> = line.split_whitespace().map(|s| s.to_owned()).collect();

Rust相关问答推荐

为什么这是&q;,而让&q;循环是无限循环?

用于判断整数块是否连续的SIMD算法.

为什么Option类型try块需要类型注释?

如何设置activx websocket actorless的消息大小限制?

如何处理闭包中的生命周期以及作为参数和返回类型的闭包?

在 Rust 中忽略 None 值的正确样式

部署Rust发布二进制文件的先决条件

Rust并发读写引起的死锁问题

如何在Rust中使用Serde创建一个自定义的反序列化器来处理带有内部标记的枚举

str 和 String 的 Rust 生命周期

为什么 Rust 的临时值有时有参考性有时没有?

borrow 匹配手臂内部的可变

错误:将自定义 proc_macro 与用Rust 的宝贝编写的属性一起使用时,无法在此范围内找到属性

&self 参数在 trait 的功能中是必需的吗?

无法理解 Rust 对临时值的不可变和可变引用是如何被删除的

如何使返回 XMLError 的方法与 anyhow::Error 兼容?

为什么指定生命周期让我返回一个引用?

为什么 Bevy 的 Trait 边界不满足 Rapier 物理插件?

类型参数不受 impl 特征、自身类型或谓词的约束

函数参数的 Rust 功能标志