[rust-dev] Why are generic integers not usable as floats?

Nathan Typanski ntypanski at gmail.com
Fri Jun 20 04:36:46 PDT 2014


On 06/19, Benjamin Striegel wrote:
> I'm actually very pleased that floating point literals are entirely
> separate from integer literals, but I can't quite explain why. A matter of
> taste, I suppose. Perhaps it stems from symmetry with the fact that I
> wouldn't want `let x: int = 1.0;` to be valid.

I agree that `let x: int = 1.0` should not be valid. But that is type
*demotion*, and with `let x: f32 = 1` we are doing type *promotion*.
Demotion is not exactly popular among languages, but promotion has
some arguments going for it.

The literal is an integer type (at least by how my brain parses it),
and it is being implicitly promoted to a float.

Now, in the following instance, I have to explicitly convert `y` to a
`f32` type before it compiles. There's no implicit promotion when
performing addition.

    let x: f32 = 1.0;
    let y: int = 1;
    print!("{}", x + y as f32);

So the question is: do we want to make a special case where we do
implicit type promotion at assignment, and nowhere else?

I say no. Either you are picky about your numeric types, or you do
type promotion everywhere, but not both. Personally I would sooner not
think about edge cases here, and just say that all numeric types
should be explicit.

       Nathan


More information about the Rust-dev mailing list