Eka
Eka

Reputation: 15000

How to return a value inside for loop in rust?

I want to port this python code

#!/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)

and its output

999
5
4
3
3
2
2
2
etc.

to rust code. This is the rust code I wrote which is identical to the above python code.

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

But its output is not the same as the python codes output

999
999
999
999
999
999
999
etc.

What is the right way to return a value in for loop using rust? Why is the my rust code outputting a different output comparing to pythons?

Upvotes: 4

Views: 8960

Answers (1)

Daniel
Daniel

Reputation: 16439

The problem is the line

let x = 2.0 * x;

let introduces a new variable, the original x is not modified. The next loop iteration will then again multiple 2.0 with the parameter x, not with the variable x from the previous loop's iteration.

You need to instead assign the value to the existing x variable (which requires marking it as mutable):

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

Upvotes: 9

Related Questions