gpt4 book ai didi

rust - 首先获取迭代器的所有内容。在使用rust

转载 作者:行者123 更新时间:2023-12-02 01:30:53 24 4
gpt4 key购买 nike

我想做什么

我有从 std::str::SplitWhitespace 返回的迭代器,我需要第一个元素,以及所有元素的向量。

我尝试过的

我尝试使用 peek。然而,这似乎需要一个可变的(我不知道为什么),我最终遇到了借用错误。

简化代码,有编译错误。

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

如果我取消对两个 println 的注释,并对错误的注释。然后它起作用了。这导致我在 println 之前添加一个克隆 let first = first.clone();。这解决了它,但我想知道是否有更好的方法。

最佳答案

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

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

注意 tokens 的类型将是 Vec<&str> -- 从 line 中借用的字符串切片向量.如果您想要一个拥有的字符串向量 ( Vec<String> ),那么您需要将每个元素映射到一个拥有的字符串:

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

关于rust - 首先获取迭代器的所有内容。在使用rust ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73344534/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com