Skip to content

Instantly share code, notes, and snippets.

@olistik
Created December 31, 2014 17:51
Show Gist options
  • Save olistik/73107fb3c1fbad115d09 to your computer and use it in GitHub Desktop.
Save olistik/73107fb3c1fbad115d09 to your computer and use it in GitHub Desktop.
Which version suits better the example?
// This version uses mem::replace()
use std::mem;
struct Fibonacci {
curr: uint,
next: uint,
}
impl Iterator<uint> for Fibonacci {
fn next(&mut self) -> Option<uint> {
let new_next = self.curr + self.next;
let new_curr = mem::replace(&mut self.next, new_next);
Some(mem::replace(&mut self.curr, new_curr))
}
}
fn fibonacci() -> Fibonacci {
Fibonacci { curr: 1, next: 1 }
}
fn main() {
println!("The first four terms of the Fibonacci sequence are: ");
for i in fibonacci().take(4) {
println!("> {}", i);
}
println!("The next four terms of the Fibonacci sequence are: ");
for i in fibonacci().skip(4).take(4) {
println!("> {}", i);
}
}
// This version doesn't use mem::replace()
struct Fibonacci {
curr: uint,
next: uint,
}
impl Iterator<uint> for Fibonacci {
fn next(&mut self) -> Option<uint> {
let (new_curr, new_next) = (self.next, self.curr + self.next);
self.curr = new_curr;
self.next = new_next;
Some(self.curr)
}
}
fn fibonacci() -> Fibonacci {
Fibonacci { curr: 0, next: 1 }
}
fn main() {
println!("The first four terms of the Fibonacci sequence are: ");
for i in fibonacci().take(4) {
println!("> {}", i);
}
println!("The next four terms of the Fibonacci sequence are: ");
for i in fibonacci().skip(4).take(4) {
println!("> {}", i);
}
}
@olistik
Copy link
Author

olistik commented Dec 31, 2014

I'm referring to the iter example

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment