Why isn't there implicit type conversion (coercion) between primitive types in Rust

Viewed 142

I am reading through Rust by Example, and I am curious about why we cannot coerce a decimal to a u8, like in the following snippet:

let decimal = 65.4321_f32;

// Error! No implicit conversion
let integer: u8 = decimal;

But explicit casting is allowed, so I don't understand why can't we have it implicit too.

Is this a language design decision? What advantages does this bring?

1 Answers

Safety is a big part of the design of Rust and its standard library. A lot of the focus is on memory safety but Rust also tries to help prevent common bugs by forcing you to make decisions where data could be lost or where your program could panic.

A good example of this is that it uses the Option type instead of null. If you are given an Option<T> you are now forced to decide what to do with it. You could decide to unwrap it and panic, or you could use unwrap_or to provide a sensible default. Your decision, but you have to make it.

To convert a f64 to a u8 you can use the as operator. It doesn't happen automatically because Rust can't decide for you what you want to happen in the case where the number is too big or too small. Or maybe you want to do something with the extra decimal part? Do you want to round it up or down or to the nearest integer?

Even the as operator is considered by some[1] to be an early design mistake, since you can easily lose data unintentionally - especially when your code evolves over time and the types are less visible because of type inference.


[1] https://github.com/rust-lang/rfcs/issues/2784#issuecomment-543180066

Related