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?
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With