Reputation: 948
I read this docs and stumbled on this line.
let an_integer = 5i32; // Suffix annotation
What is this mean? I am assuming that it have 5 as value and i32 as integer type. Is that correct?
Upvotes: 3
Views: 1196
Reputation: 76629
Yes, that's correct. When you write the literal 5
in a program, it could be interpreted as a variety of types. (A literal is a value, such as 5
, which is written directly into the source code instead of being computed.) If we want to express that a literal is of a certain type, we can append ("suffix") the type to it to make it explicit, as in 5i32
.
This is only done with certain built-in types, such as integers and floating-point numbers, but it can come in handy in some cases. For example, the following is not valid:
fn main() {
println!("{}", 1 << 32);
}
That's because if you specify no type at all for an integer, it defaults to i32
. Since it's not valid to shift a 32-bit integer by 32 bits, Rust produces an error.
However, we can write this and it will work:
fn main() {
println!("{}", 1u64 << 32);
}
That's because now the integer is a u64
and it's in range.
Upvotes: 10