No automatic type cast in rust


#1

Why don’t we have automatic type cast in rust ?

// Accuracy function
fn accuracy(tp:i32,tn:i32,total:i32) -> f32 { 
	(tp as f32 + tn as f32 )/(total as f32)
}

If I did not use the as for manually type casting, the compiler would throw me error[E0308]: mismatched types.


#2

Implicit casting is arguably a bad idea, and makes code harder to understand.

After all, if all you have is:

(tp + tn) / total

Then the question becomes: where does the cast happen? Does it do the math as i32, then cast? Does it cast immediately to f32? In more complicated situations involving multiple types, you could have an explosion of possibilities, only one of which is correct.

It may be convenient, but it’s also often not worth the mental overhead.


#3

Thanks for the reply.

I was wondering why we don’t have automatic type casting in rust, like why can’t the compiler understand that(tp + tn) / total is a float type.


#4

Is it? Even if Rust did an implicit cast i32 -> f32 here, it would probably take the result of the division and cast to f32. It wouldn’t be able to infer that you probably want to cast before the division. As @DanielKeep said, having to decide where to cast (even for tp + tn it makes a big difference due to possible overflow) is beneficial.

(In case you think a/b should always result in a float: Integer division yielding integers is a common, and useful, thing in strongly typed languages.)


#5

Automatic Typecast does not work when you are returning a different datatype compared to the input argument datatype for the function. I had to use as for type casting.

I agree the type cast works fine in normal arithmetic operations, sorry for the misleading question.

Ref :
http://angrylawyer.github.io/a-dabblers-adventures-in-rust/#slide6


#6

And even in less strongly types languages!

irb(main):001:0> 3/2
=> 1
irb(main):002:0> _.class
=> Fixnum

#7

In Python, the intent was so ambiguous that PEP 238 gave it separate operators, a/b and a//b.