7

In https://doc.rust-lang.org/book/primitive-types.html#numeric-types, it said that in

let x = 42; // x has type i32

That means x has the type i32 as default.

But in http://rustbyexample.com/cast/literals.html, it says that

Unsuffixed literal, their types depend on how they are used

I know I can't use i32 to index the vector, but the following code works:

fn main() {
    let v = vec![1, 2, 3, 4, 5];

    let j = 1;  // j has default type i32? or it has type when it is first used?
                // And what is the type of 1?

    println!("{}", v[1]); // is 1 a usize?
    println!("{}", v[j]);
}

So, what is the type of a literal integral value?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Regis
  • 346
  • 1
  • 10

1 Answers1

13

From the language reference:

The type of an unsuffixed integer literal is determined by type inference:

  • If an integer type can be uniquely determined from the surrounding program context, the unsuffixed integer literal has that type.

  • If the program context under-constrains the type, it defaults to the signed 32-bit integer i32.

  • If the program context over-constrains the type, it is considered a static type error.

On the line

println!("{}", v[1]); // is 1 a usize?

the surrounding program context requires 1 to be an usize (because that's what the [] operator needs), so yes, here 1 will have the type usize.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
sepp2k
  • 363,768
  • 54
  • 674
  • 675
  • 4
    It's also worth mentioning, that the type is not inferred the "first time it is used". If it is used in differing contexts, you will get a compiler error. It will simply not be able to determine the type. – Keozon Aug 09 '16 at 17:59