rust - Subtraction not implemented for f32? -


when compiling 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 f32)         .map(|s| (s - 4) / 2)         .map(|s| s i32)         .collect(); } 

i error saying:

the trait core::ops::sub<_> not implemented type f32

why this?

rust stricter other languages when comes manipulating primitive types. math operators require same type on both sides (with exception of bit shifts, expect usize right-hand side operand). rust not automatically cast values 1 primitive numeric type another: must insert explicit cast in code. code demonstrates situation:

fn main(){     let a: i32 = 2;     let b: i8 = 3;     println!("{}", + b); } 

it fails compile following errors:

<anon>:4:24: 4:25 error: mismatched types:  expected `i32`,     found `i8` (expected i32,     found i8) [e0308] <anon>:4     println!("{}", + b);                                 ^ <std macros>:2:25: 2:56 note: in expansion of format_args! <std macros>:3:1: 3:54 note: in expansion of print! (defined in <std macros>) <anon>:4:5: 4:27 note: in expansion of println! (defined in <std macros>) <anon>:4:24: 4:25 help: see detailed explanation e0308 <anon>:4:20: 4:25 error: trait `core::ops::add<i8>` not implemented type `i32` [e0277] <anon>:4     println!("{}", + b);                             ^~~~~ <std macros>:2:25: 2:56 note: in expansion of format_args! <std macros>:3:1: 3:54 note: in expansion of print! (defined in <std macros>) <anon>:4:5: 4:27 note: in expansion of println! (defined in <std macros>) <anon>:4:20: 4:25 help: see detailed explanation e0277 

your situation similar, has particularity you're mixing integers , floats. in rust, integer , float literals assigned type based on context. that's why set a 2 , b 3 above: 2 not i32, implicitly typed i32 if context requires it.

in case, you're trying subtract integer f32. error message mentions sub<_>; _ represents type of 4 literal compiler wasn't able figure out.

the solution use float literals instead of integer literals:

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 f32)         .map(|s| (s - 4.0) / 2.0)         .map(|s| s i32)         .collect::<vec<_>>(); } 

Comments

Popular posts from this blog

sql - VB.NET Operand type clash: date is incompatible with int error -

SVG stroke-linecap doesn't work for circles in Firefox? -

python - TypeError: Scalar value for argument 'color' is not numeric in openCV -