[rust-dev] Warn about implicit integer conversion
graydon at mozilla.com
Tue Dec 18 16:15:52 PST 2012
On 12-12-18 10:35 AM, Michael Neumann wrote:
> let a: u8 = 10_000; // this does not fit inside u8!
> io::println(fmt!("%?", a)); // print "10"
> I would have expected that rust would warn me if I try to assign an
> integer constant that doesn't fit into the types range.
> Maybe there exists a warning that I can enable?
Yikes. Unfortunate. This is another of those cases I dreaded the
occurrence of when finally argued into accepting literal-suffix
inference. Oh well.
I think I know what's going on here, and it's a bit of a sad story, but
one we can probably salvage some of. I'll file a bug.
Note that if you write "10_000u8" (explicitly giving a suffix), rustc
complains as it should.
What's happening instead is that you're invoking literal-suffix
inference by not providing a suffix, and it's deciding that you mean
u8 (correctly), and it's _then_ accepting that in 2s complement
arithmetic, overflow of that sort is completely legitimate. Which, you
know, it is. If you had written this as:
let a : u8 = 100 * 100;
I suspect your reaction would have been less shocked. It feels a bit
more reasonable, somehow.
But it comes down to the same issue: we draw a line about which
overflows to check at compile time. I agree it'd be nice to check
And possibly, now that we have a better-defined notion of an integer
constant expression, we might consider _all_ constant-expression
overflows to be compile-time errors. I'm not sure if that's wise or not;
it'll make abstracting a constant into a function more observable
(you'll be toggling overflow checks) and there might be important
intentional-overflow expressions that it makes hard, or impossible, to
write. We can explore this matter more in the bug itself.
Probably lkuper has more to say about this, but for the time being,
watch this bug and we'll try to fix it up at least a little more in the
next release cycle:
 Note: it is _not_ doing size-based type inference. We decided not to
do that. It will simply pick either a unique type from its environment
(u8) or an under-constrained type variable if it can't figure out which
type you mean, and emit an error.
More information about the Rust-dev