How to swap two variables?

后端 未结 3 1243
孤城傲影
孤城傲影 2020-12-01 13:55

What is the closest equivalent Rust code to this Python code?

a, b = 1, 2
a, b = b, a + b

I am trying to write an iterative Fibonacci funct

3条回答
  •  無奈伤痛
    2020-12-01 14:46

    In addition, a better way to implement the Fibonacci sequence in Rust is using the Iterator trait:

    // Iterator data structure
    struct FibIter(u32, u32);
    
    // Iterator initialization function
    fn fib() -> FibIter {
        FibIter(0u32, 1u32)
    }
    
    // Iterator trait implementation
    impl Iterator for FibIter {
        type Item = u32;
        fn next(&mut self) -> Option {
            *self = FibIter(self.1, self.1 + self.0);
            Some(self.0)
        }
    }
    
    fn main() {
        println!("{:?}", fib().take(15).collect::>());
    }
    

    See The Rust Programming Language chapter on iterators.

提交回复
热议问题