Hacker News new | ask | show | jobs
by red75prime 2918 days ago
> if you write `let x = 42;` the type is inferred as `i32`.

It can be influenced by the x's usage.

    let x = 42;
    let y = x/2 + 21u32;
x is u32 here.
3 comments

Yes the rule is that it defaults to i32 only if there's absolutely no way to infer the exact type by use like in your example. So in practice it almost never happens because as soon as you use the value in an operation or function call the compiler knows the exact type. One exception would be code like:

    fn main() {
        for i in 0..10 {
            println!("{}", i);
        }
    }
Here there's no way for the compiler to know what exact integer type is expected so it defaults to i32. There was a debate about this, I was personally in opposition but in my experience it mostly occurs on small "hello world" examples and code snippets so it doesn't really matter. I've never encountered any issues stemming from this rule so far. At least they got rid of the "int" and "uint" types which is a great thing in my opinion.
GP is talking about the default value for "unconstrained" literals, yours is constrained by the second expression: assuming just the stdlib,

* Add<u32> is implemented for u32 and &u32

* thus x/2: (u32 | &u32)

* there's no Div<Output=&u32> so x/2: u32

* Div<Output=u32> only is only "Div<u32> for u32"

* thus x: u32

Interesting... I'm a newbie at Rust, and expected y to be a float, because of the division.

But it turns out

    let x = 11;
    let y = 11/2;
==> y = 5 Given how type safety is important to Rust, I expected this to panic rather than do an automatic cast.
There is no type safety issue, and there is no cast. Div on integral types is explicitly implementing as an integer/truncating division: https://doc.rust-lang.org/src/core/ops/arith.rs.html#436-452

There would be no type-safety issue or cast if it were implemented as a real division either, incidentally.

There is room to argue Div should not have been implemented at all on integral types (as in Haskell where integer division is a separate operation entirely), but that's a completely different issue.