首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将嵌套的for循环转换为迭代器

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

Stack Overflow用户
提问于 2019-06-28 17:51:03
回答 1查看 983关注 0票数 1

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

代码语言:javascript
复制
#![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

我得到两个错误:

代码语言:javascript
复制
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()

EN

回答 1

Stack Overflow用户

发布于 2019-06-28 19:56:30

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

另请参见this answer

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56804678

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档