Literals
Numeric literals can be type annotated by adding the type as a suffix.
As an example, to specify that the literal
42
should have the typei32
, write42i32
.
The type of unsuffixed numeric literals will depend on how they are used:
If no constraint exists, the compiler will use
i32
for integers, andf64
for floating-point numbers.
unsuffixed numeric literias depend on how they are used
fn main() { // Suffixed literals, their types are known at initialization let x = 1u8; let y = 2u32; let z = 3f32; // Unsuffixed literals, their types depend on how they are used let i = 1; let f = 1.0; // `size_of_val` returns the size of a variable in bytes println!("size of `x` in bytes: {}", std::mem::size_of_val(&x)); println!("size of `y` in bytes: {}", std::mem::size_of_val(&y)); println!("size of `z` in bytes: {}", std::mem::size_of_val(&z)); println!("size of `i` in bytes: {}", std::mem::size_of_val(&i)); println!("size of `f` in bytes: {}", std::mem::size_of_val(&f)); }
- Suffixed literals, their types are known at initialization
- Unsuffixed literals, their types depend on how they are used
There are some concepts used in the previous code that haven’t been explained yet, here’s a brief explanation for the impatient readers: