29

When doing something like:

let mut sum = 5 + 10;

What is the exact type of sum? Is it an arbitrary-size type which can’t be overflowed?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
user2284570
  • 2,891
  • 3
  • 26
  • 74
  • The default integer type is a signed one, but I cannot say much about the size – Boiethios Apr 29 '19 at 12:26
  • @hegel5000 what I wonder is if I do something after like `mut = mut + 20000004359729432973429745297452997799` there will be an overflow or it creates a special type which can store integers with arbitrary number of bytes ? – user2284570 Apr 29 '19 at 12:28
  • 2
    Relevant: https://stackoverflow.com/q/38854408/1233251 – E_net4 Apr 29 '19 at 12:32
  • 1
    Possible duplicate of [Do literal integral values have a specific type in Rust?](https://stackoverflow.com/questions/38854408/do-literal-integral-values-have-a-specific-type-in-rust) – Sven Marnach Apr 29 '19 at 13:13

1 Answers1

36

There is RFC 212, which states:

Integer literals whose type is unconstrained will default to i32

If you want there is a clippy lint default_numeric_fallback that can warn you about unwanted fallback.

Stargateur
  • 24,473
  • 8
  • 65
  • 91
  • Where was it validated? – Boiethios Apr 29 '19 at 12:27
  • 2
    @FrenchBoiethios There is a link to the issue but I believe that the RFC repository only merge a RFC when it's accepted so by definition if a RFC is on the master branch, it has been accepted and still up to date. "Eventually, somebody on the core team will either accept the RFC by merging the pull request, at which point the RFC is 'active', or reject it by closing the pull request." https://github.com/rust-lang/rfcs/blob/master/text/0002-rfc-process.md – Stargateur Apr 29 '19 at 12:30
  • @Stargateur is it also the same for integers returned by functions ? – user2284570 Apr 29 '19 at 12:34
  • 4
    @user2284570 functions require to be explicit, so you can't write such functions. You only way would be to use generic, and let the compiler infer the type of the generic with a variable you didn't type, for exemple: https://play.integer32.com/?version=nightly&mode=debug&edition=2018&gist=95dcc2095b4b1744f314d85e54c58195 – Stargateur Apr 29 '19 at 12:42
  • Did they change the default? My IDE is telling me my numbers are i64. Maybe it's inferring that type from somewhere, idk. – Hutch Moore Jul 27 '20 at 17:49
  • Never mind, it was coming from a library method return value, and that cascaded down to my integers of unmarked type. – Hutch Moore Jul 27 '20 at 17:59