How to replace two variables?

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 function. I have Python code that I want to convert to Rust. Everything is fine except for the swap part.

 def fibonacci(n): if n < 2: return n fibPrev = 1 fib = 1 for num in range(2, n): fibPrev, fib = fib, fib + fibPrev return fib 
+13
rust
source share
2 answers

When replacing variables, it is most likely that you need to create new bindings for a and b .

 fn main() { let (a, b) = (1, 2); let (b, a) = (a, a + b); } 

However, in your particular case, there is no good solution. When you do as above, you always create new bindings for a and b , but you want to change the existing bindings. One solution I know is to use a temporary:

 fn fibonacci(n: u64) -> u64 { if n < 2 { return n; } let mut fib_prev = 1; let mut fib = 1; for _ in 2..n { let next = fib + fib_prev; fib_prev = fib; fib = next; } fib } 

You can also make sure you mutate the tuple:

 fn fibonacci(n: u64) -> u64 { if n < 2 { return n; } let mut fib = (1, 1); for _ in 2..n { fib = (fib.1, fib.0 + fib.1); } fib.1 } 

You may also be interested in sharing the contents of two pieces of memory. 99 +% of the time, you want to re-bind the variables, but a very small amount of time you want to change things in place:

 fn main() { let (mut a, mut b) = (1, 2); std::mem::swap(&mut a, &mut b); println!("{:?}", (a, b)); } 

Please note that it is not concise to make this exchange and add values ​​together in one step.

See also:

  • Can I destruct a tuple without binding the result to a new variable in the let / match / for statement?
+19
source share

Also, the best way to implement a Fibonacci sequence in Rust uses an 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<u32> { *self = FibIter(self.1, self.1 + self.0); Some(self.0) } } fn main() { println!("{:?}", fib().take(15).collect::<Vec<_>>()); } 

See the Rust Programming Language section on the iterators chapter .

+5
source share