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

Daniel Micay danielmicay at gmail.com
Fri Jun 20 10:25:51 PDT 2014


On 20/06/14 07:36 AM, Nathan Typanski wrote:
> 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

It wouldn't be a type conversion at all. The literal `1` does not have
the type `int`, it's a generic integer literal with an inferred type.

In Haskell, `1` is a generic *number* literal and can be inferred as any
kind of integer, floating point, fixed point or rational type.

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 819 bytes
Desc: OpenPGP digital signature
URL: <http://mail.mozilla.org/pipermail/rust-dev/attachments/20140620/1b1cb30e/attachment.sig>


More information about the Rust-dev mailing list