gpt4 book ai didi

for-loop - 将嵌套的 for 循环转换为迭代器

转载 作者:行者123 更新时间:2023-11-29 08:31:26 26 4
gpt4 key购买 nike

这里是 Rust 新手,我在将以下嵌套 for 循环转换为迭代器时遇到了问题:

#![allow(unused)]

use std::io::Error;

fn main() {
let realms = vec!["realm".to_string()];
let auctions = get_auctions(&realms);
}

pub struct Auction;
pub struct RealmAuctionFile;

fn get_realm_auctions(file: &RealmAuctionFile) -> Result<Vec<Auction>, Error> {
let auctions = vec![Auction {}];

Ok(auctions)
}

fn get_realm_auction_files(realm: &str) -> Result<Vec<RealmAuctionFile>, Error> {
let files = vec![RealmAuctionFile {}];

Ok(files)
}

pub fn get_auctions(realms: &Vec<String>) -> Result<Vec<Auction>, Error> {
let mut auctions = vec![];

for realm in realms.iter() {
let files = get_realm_auction_files(realm)?;

for file in files.iter() {
let mut realm_auctions = get_realm_auctions(file)?;

auctions.append(&mut realm_auctions);
}
}

Ok(auctions)
}

pub fn get_auctions_with_iterator(realms: &Vec<String>) -> Result<Vec<Auction>, Error> {
let auctions = realms
.iter()
.flat_map(|realm| {
let realms_auctions: Vec<Auction> = get_realm_auction_files(realm)?
.iter()
.flat_map(|file| {
let auctions = get_realm_auctions(file)?;

Ok(auctions)
})
.collect();

Ok(realms_auctions)
})
.collect();

Ok(auctions)
}

Playground

我得到两个错误:

error[E0277]: a collection of type `std::vec::Vec<Auction>` cannot be built from an iterator over elements of type `std::vec::Vec<Auction>`
--> src/main.rs:52:18
|
52 | .collect();
| ^^^^^^^ a collection of type `std::vec::Vec<Auction>` cannot be built from `std::iter::Iterator<Item=std::vec::Vec<Auction>>`
|
= help: the trait `std::iter::FromIterator<std::vec::Vec<Auction>>` is not implemented for `std::vec::Vec<Auction>`

error[E0277]: a collection of type `std::vec::Vec<Auction>` cannot be built from an iterator over elements of type `std::vec::Vec<Auction>`
--> src/main.rs:56:10
|
56 | .collect();
| ^^^^^^^ a collection of type `std::vec::Vec<Auction>` cannot be built from `std::iter::Iterator<Item=std::vec::Vec<Auction>>`
|
= help: the trait `std::iter::FromIterator<std::vec::Vec<Auction>>` is not implemented for `std::vec::Vec<Auction>`

此外,我无法将 .unwrap()“转换”为更惯用的 ?

最佳答案

不要展开。而是生成 Result 的迭代器并利用 Result implements FromIterator 的事实将其收集到 Result<Vec> 中.

另见 this answer .

关于for-loop - 将嵌套的 for 循环转换为迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56804678/

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