What should be the return type of iter (). Cloned (). Filter (). Map ()

So, I return the iterator as follows:

pub fn get_iter_names(&self) -> ??? { self.nodes.iter().cloned() .filter(|x| x.is_some()) .map(|x| x.unwrap().name) } 

where self.nodes is Vec<Option<Node>> , and Node has filed name . The question is what the return type should be. My compiler says core::iter::Map<core::iter::Filter<core::iter::Cloned<core::slice::Iter<'_, core::option::Option<core::node::ComputeNode>>>, [ closure@src /core/graph.rs:931:12: 931:27]>, [ closure@src /core/graph.rs:932:9: 932:28]> but the problem is that I don’t know how to specify clousure as a type?

What is the right way to do this?

+4
source share
1 answer

I am sure this question was asked in Stackoverflow, but I cannot find it, so you go.

Rust unboxed closures have anonymous types generated by the compiler. Therefore, there is no way to specify them in a signature type. This means that it is not possible to return unboxed closures by value.

The usual solution is to set the return value:

 pub fn get_iter_names(&self) -> Box<Iterator<Item=???>> { Box::new(self.nodes.iter().cloned() .filter(|x| x.is_some()) .map(|x| x.unwrap().name)) } 

You must specify any field of type name instead of ??? (I can't get it out of your code alone).

There is an RFC to allow the return of unboxed values ​​that implement some features, but is delayed. According to the discussion in this RFC PR, it seems that at least some work has been done lately, so it may be available in Rust (relatively) in the near future.

+5
source

All Articles