如何在 Rust 的 for 循环中返回一个值?

Eka*_*Eka 2 rust rust-cargo

我想移植这个python代码

#!/usr/bin/python
# -*- coding: utf-8 -*-

def testing(x, y):
    for i in range(y):
        x = 2.0 * x
        if x > 3.5:
            return i
    return 999


for i in range(20):
    print testing(float(i) / 10, 15)
Run Code Online (Sandbox Code Playgroud)

和它的输出

999
5
4
3
3
2
2
2
etc.
Run Code Online (Sandbox Code Playgroud)

生锈代码。这是我写的 rust 代码,与上面的 python 代码相同。

fn testing(x: f32, y: i32) -> i32 {
    for i in 0..y {
        let x = 2.0 * x;
        if x > 3.5 {
            return i;
        }
    }
    return 999;
}

fn main() {
    for i in 0..20 {
        let a = i as f32;
        println!("{}", testing(a / 10.0, 15));
    }
}
Run Code Online (Sandbox Code Playgroud)

但它的输出与python代码输出不同

999
999
999
999
999
999
999
etc.
Run Code Online (Sandbox Code Playgroud)

使用 rust 在 for 循环中返回值的正确方法是什么?为什么与 python 相比,我的 rust 代码输出不同的输出?

Dan*_*iel 6

问题是线路

let x = 2.0 * x;
Run Code Online (Sandbox Code Playgroud)

let引入了一个新的变量,原来x的没有修改。下一次循环迭代将再次与参数 2.0 相乘x,而不是与x前一次循环迭代中的变量相乘。

您需要将值分配给现有x变量(这需要将其标记为mut能够):

fn testing(mut x: f32, y: i32) -> i32 {
    for i in 0..y {
        x = 2.0 * x;
        if x > 3.5 {
            return i;
        }
    }
    return 999;
}

fn main() {
    for i in 0..20 {
        let a = i as f32;
        println!("{}", testing(a / 10.0, 15));
    }
}
Run Code Online (Sandbox Code Playgroud)