如何交换两个变量? [英] How to swap two variables?

查看:43
本文介绍了如何交换两个变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

与此 Python 代码最接近的等效 Rust 代码是什么?

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

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

我正在尝试编写一个迭代斐波那契函数.我有要转换为 Rust 的 Python 代码.一切都很好,除了交换部分.

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

推荐答案

在交换变量时,您最可能想要的是为 a 和 <创建新的绑定代码>b.

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);
}

但是,在您的实际情况中,稳定的 Rust 没有很好的解决方案.执行上述操作时,您总是为 ab 创建新绑定,但您的案例想要修改现有绑定.我知道的一种解决方案是使用临时:

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
}

nightly Rust 中,您可以使用 解构赋值:

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
}

您可能还对交换两块内存的内容感兴趣.在 99+% 的情况下,您希望重新绑定变量,但在极少数情况下您希望就地"更改内容:

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))
    })
}

另见:

这篇关于如何交换两个变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆