Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I multiply an integer and a floating value together and display the result as a floating value in Rust? [duplicate]

Tags:

rust

I have the following code:

struct Stuff {
    thing: i8
}

fn main(){
    let theStuff = Stuff { thing: 1 };
    println!("{}", theStuff.thing * 1.5);
}

I get the following on compilation:

error[E0277]: the trait bound `i8: std::ops::Mul<{float}>` is not satisfied
 --> IntFloatMultiply.rs:7:32
  |
7 |  println!("{}", theStuff.thing * 1.5);
  |                                ^ no implementation for `i8 * {float}`
  |
  = help: the trait `std::ops::Mul<{float}>` is not implemented for `i8`

I've read some other posts including a bunch of stuff that is pretty well over my head (including https://stackoverflow.com/a/44552464/1678392). I don't care about the technical details, what or why, if I don't have a concrete answer to start from. How do I get this code to compile so it displays a float result?

like image 843
skia.heliou Avatar asked Feb 06 '18 01:02

skia.heliou


1 Answers

Assuming you want the result of 1 * 1.5 to be a floating point number, you can cast thing to f64 with the as operator:

fn main() {
    let the_stuff = Stuff { thing: 1 };
    println!("{}", the_stuff.thing as f64 * 1.5);
}

This prints 1.5. Rust forces you to be explicit about how different numeric types interact.

Assuming you're always multiplying an i8 by 1.5, then you can fit the result in a f32 return type:

fn main() {
    let the_stuff = Stuff { thing: i8::max_value() };
    println!("{}", the_stuff.thing as f32 * 1.5);
}
like image 84
Taylor Wood Avatar answered Oct 21 '22 17:10

Taylor Wood