Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do literal integral values have a specific type in Rust?

Tags:

literals

rust

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?

like image 559
Regis Avatar asked Aug 09 '16 15:08

Regis


1 Answers

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.

like image 112
sepp2k Avatar answered Sep 22 '22 11:09

sepp2k