Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify types during for-in loop? [duplicate]

Tags:

loops

rust

See this super simple playpen

fn main() {
    for i in 0..10 {
        println!("{}", i*0.5); 
    }
}

The result of compilation on Rust 1.0-beta.2 is "error: the trait core::ops::Mul<_> is not implemented for the type _"

I think that I need to specify the type of i somehow but I am struggling to find the documentation on how to do so.

like image 812
user25064 Avatar asked Apr 19 '15 15:04

user25064


1 Answers

When an integral variable isn't otherwise constrained, it will fall back to i32. The problem is that you have both an unconstrained integer and floating-point number, so it's not clear how to multiply them (hence the error). Since you have to cast them to multiply anyway, I'd just cast the loop variable in the print statement:

fn main() {
    for i in 0..10 {
        println!("{}", (i as f64) * 0.5); 
    }
}

I don't know if it's possible to actually specify the type of the loop variable. In cases like that, I've just made sure the range is clearly defined:

fn main() {
    for i in 0..10_u16 {
        println!("{}", i * 0.5); 
    }
}

however, this still has the same error (but with a bit more detail):

<anon>:3:24: 3:31 error: the trait `core::ops::Mul<_>` is not implemented for the type `u16` [E0277]
<anon>:3         println!("{}", i * 0.5); 
                                ^~~~~~~

As I alluded to earlier, you can't implicitly multiply integers and floating-point numbers. You have to decide what you want it to mean.

like image 176
Shepmaster Avatar answered Oct 22 '22 21:10

Shepmaster