Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
735 views
in Technique[技术] by (71.8m points)

rust - How to swap 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 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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

When swapping variables, the most likely thing you want is to create new bindings for a and b.

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

However, in your actual case, there isn't a nice solution in stable Rust. When you do as above, you always create new bindings for a and b, but your case wants to modify the existing bindings. One solution I know of 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 could also make it so that 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
}

In nightly Rust, you can use destructuring assignment:

#![feature(destructuring_assignment)]

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

You may also be interested in swapping 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));
}

Note that it's not concise to do this swap and add the values together in one step.

For a very concise implementation of the Fibonacci sequence that returns an iterator:

fn fib() -> impl Iterator<Item = u128> {
    let mut state = [1, 1];
    std::iter::from_fn(move || {
        state.swap(0, 1);
        let next = state.iter().sum();
        Some(std::mem::replace(&mut state[1], next))
    })
}

See also:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...