如何迭代 Option<Vec<_>>? [英] How can I iterate on an Option&lt;Vec&lt;_&gt;&gt;?

查看:65
本文介绍了如何迭代 Option<Vec<_>>?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对 Option> 进行迭代.

I am trying to iterate on on Option<Vec<>>.

#[derive(Debug)]
pub struct Person {
    pub name: Option<String>,
    pub age: Option<u64>,
}

#[derive(Debug)]
pub struct Foo {
    pub people: Option<Vec<Person>>,
}

我天真地使用

for i in foo.people.iter() {
    println!("{:?}", i);
}

不是遍历 Vec 的所有元素,我实际上是在显示整个 Vec.这就像我正在迭代 Option 的唯一引用.

Instead of iterating over all the elements of the Vec, I am actually displaying the whole Vec. It is like I am iterating over the only reference of the Option.

使用以下内容,我正在迭代 Vec 内容:

Using the following, I am iterating over the Vec content:

for i in foo.people.iter() {
    for j in i.iter() {
        println!("{:?}", j);
    }
}

我不确定这是最令人愉快的语法,我相信您应该首先打开 Option 以实际迭代集合.

I am not sure this is the most pleasant syntax, I believe you should unwrap the Option first to actually iterate on the collection.

然后我看不出你可以在哪里使用 Option::iter,如果你总是有一个单一的引用.

Then I don't see where you can actually use Option::iter, if you always have a single reference.

这里是游乐场.

推荐答案

Option 有一个 iter 方法迭代可能包含的值",即提供 Option 中的单个值(如果选项是 Some),或者根本没有值(如果选项是 None).因此,如果您想将选项视为容器,其中 None 表示容器为空,而 Some 表示它包含单个元素,则它很有用.

Option has an iter method that "iterates over the possibly contained value", i.e. provides either the single value in the Option (if option is Some), or no values at all (if the option is None). As such it is useful if you want to treat the option as a container where None means the container is empty and Some means it contains a single element.

要迭代底层元素的值,您需要从 foo.people.iter() 切换到 foo.people.unwrap().iter()foo.people.unwrap_or_else(Vec::new).iter(),这取决于您是否希望程序在遇到 None 人时恐慌或不迭代.

To iterate over the underlying element's values, you need to switch from foo.people.iter() to either foo.people.unwrap().iter() or foo.people.unwrap_or_else(Vec::new).iter(), depending on whether you want the program to panic or to not iterate when encountering None people.

可编译示例在操场上.

这篇关于如何迭代 Option<Vec<_>>?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆