Last active
August 18, 2020 14:17
-
-
Save umcconnell/d174b0aa2ddb5355261070f2c330f437 to your computer and use it in GitHub Desktop.
Generate the Fibonacci Sequence in Rust.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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