Hide private type in exported signature

In this example, NoGood is a pub, and AtomWord is private.

I would like to export an instance of IntoIterator , but I can not, because this huge type definition for IntoIter includes a reference to AtomWord .

I understand that I can create an Iterator wrapper that just passes calls to the base iterator, but that is a lot of templates. I can't figure out how to make a general wrapper class (without hitting the target, which should hide the AtomWord type).

 impl <'a> IntoIterator for &'a NoGood { type Item = Literal; type IntoIter = FilterMap<slice::Iter<'a, AtomWord>, fn(&AtomWord) -> Option<Literal>>; fn into_iter(self) -> Self::IntoIter { (&self.lits).into_iter().filter_map(as_opt_lit) } } 
+4
source share
1 answer

No, you cannot hide a private type in a public method. It is publicly available, which means that people should see it.

As delnan mentions , the wrapper structure is common to iterators. It also has zero execution cost:

 struct Iter<'a>(FilterMap<slice::Iter<'a, AtomWord>, fn(&AtomWord) -> Option<Literal>>); impl<'a> Iterator for Iter<'a> { type Item = Literal; fn next(&mut self) -> Option<Literal> { self.0.next() } } impl<'a> IntoIterator for &'a NoGood { type Item = Literal; type IntoIter = Iter; fn into_iter(self) -> Self::IntoIter { Iter((&self.lits).into_iter().filter_map(as_opt_lit)) } } 

And as ker mentions , you can install it. This saves programmer input time, but due to memory allocation at runtime:

 impl<'a> IntoIterator for &'a NoGood { type Item = Literal; type IntoIter = Box<Iterator<Item = Literal>>; fn into_iter(self) -> Self::IntoIter { Box::new((&self.lits).into_iter().filter_map(as_opt_lit)) } } 

Note that I did not try to compile any of them because you did not provide MCVE and thus your code does not compile in any way.

+2
source

All Articles