Skip to content

Instantly share code, notes, and snippets.

@umcconnell
Last active August 18, 2020 14:17
Show Gist options
  • Save umcconnell/d174b0aa2ddb5355261070f2c330f437 to your computer and use it in GitHub Desktop.
Save umcconnell/d174b0aa2ddb5355261070f2c330f437 to your computer and use it in GitHub Desktop.
Generate the Fibonacci Sequence in Rust.
pub struct Fib {
a: u32,
b: u32,
count: i32,
}
impl Fib {
pub fn new(count: i32) -> Fib {
Fib { a: 1, b: 1, count }
}
}
impl Iterator for Fib {
type Item = u32;
fn next(&mut self) -> Option<Self::Item> {
self.count -= 1;
if self.count >= 0 {
let curr = self.a;
self.a = self.b;
self.b = curr + self.a;
Some(curr)
} else {
None
}
}
}
fn main() {
let fib = Fib::new(10);
for i in fib {
println!("{}", i);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment