Hiding Internals When Returning Iterators in Rust
I wrote a function that returns an iterator that lists all Fibonacci numbers:
fn fib<'a>() -> Unfold<'a, int, (int, int)> { Unfold::new((1, 1), |st| { let (a, b) = *st; *st = (b, a + b); Some(a) }) }
Unfortunately, the return type provides many of the internal functions of this function, such as the type of internal state (int, int)
. What are my options for hiding these internals?
source to share
As A .B pointed out, the standard method is to wrap it in a struct:
pub struct Fibonacci { inner: Unfold<'static, i32, (i32, i32)> } impl Iterator for Fibonacci { type Item = i32; fn next(&mut self) -> Option<i32> { self.inner.next() } } pub fn fib() -> Fibonacci { Fibonacci { inner: Unfold::new((1, 1), |st| { let (a, b) = *st; *st = (b, a + b); Some(a) }) } }
By the way, I also fixed a few nits:
-
As Chris Morgan notes, it is clearer to use it
'static
as a lifetime. -
int
(akaisize
) should not be used here since the Fibonacci sequence is independent of the pointer size. I changed it to a more idiomatic onei32
.
source to share