When compiling the following code:
use std::io::*;
fn main(){
let reader = stdin();
let nums = reader.lock()
.lines().next().unwrap().unwrap()
.split_whitespace()
.map(|s| s.parse::<i32>().unwrap())
.map(|s| s as f32)
.map(|s| (s - 4) / 2)
.map(|s| s as i32)
.collect();
}
I get an error saying:
the trait
core::ops::Sub<_>
is not implemented for the typef32
Why is this?
Rust is stricter than some other languages when it comes to manipulating primitive types. Most math operators require the same type on both sides (with the exception of bit shifts, which expect a
usize
as the right-hand side operand). Rust will not automatically cast values from one primitive numeric type to another: you must insert an explicit cast in the code. This code demonstrates the situation:It fails to compile with the following errors:
Your situation is similar, but it has the particularity that you're mixing integers and floats. In Rust, integer and float literals are assigned a type based on context. That's why I could set
a
to2
andb
to3
above:2
is not always ani32
, but it is implicitly typed asi32
if the context requires it.In your case, you're trying to subtract an integer from an
f32
. The error message mentionsSub<_>
; that_
represents the type of the4
literal that the compiler wasn't able to figure out.The solution is simply to use float literals instead of integer literals: