]>
Commit | Line | Data |
---|---|---|
2c00a5a8 XL |
1 | # Literals |
2 | ||
3 | Numeric literals can be type annotated by adding the type as a suffix. As an example, | |
4 | to specify that the literal `42` should have the type `i32`, write `42i32`. | |
5 | ||
6 | The type of unsuffixed numeric literals will depend on how they are used. If no | |
7 | constraint exists, the compiler will use `i32` for integers, and `f64` for | |
8 | floating-point numbers. | |
9 | ||
10 | ```rust,editable | |
11 | fn main() { | |
12 | // Suffixed literals, their types are known at initialization | |
13 | let x = 1u8; | |
14 | let y = 2u32; | |
15 | let z = 3f32; | |
16 | ||
72b1a166 | 17 | // Unsuffixed literals, their types depend on how they are used |
2c00a5a8 XL |
18 | let i = 1; |
19 | let f = 1.0; | |
20 | ||
21 | // `size_of_val` returns the size of a variable in bytes | |
22 | println!("size of `x` in bytes: {}", std::mem::size_of_val(&x)); | |
23 | println!("size of `y` in bytes: {}", std::mem::size_of_val(&y)); | |
24 | println!("size of `z` in bytes: {}", std::mem::size_of_val(&z)); | |
25 | println!("size of `i` in bytes: {}", std::mem::size_of_val(&i)); | |
26 | println!("size of `f` in bytes: {}", std::mem::size_of_val(&f)); | |
27 | } | |
28 | ``` | |
29 | ||
30 | There are some concepts used in the previous code that haven't been explained | |
31 | yet, here's a brief explanation for the impatient readers: | |
32 | ||
2c00a5a8 XL |
33 | * `std::mem::size_of_val` is a function, but called with its *full path*. Code |
34 | can be split in logical units called *modules*. In this case, the | |
35 | `size_of_val` function is defined in the `mem` module, and the `mem` module | |
36 | is defined in the `std` *crate*. For more details, see | |
37 | [modules][mod] and [crates][crate]. | |
38 | ||
dc9dc135 XL |
39 | [mod]: ../mod.md |
40 | [crate]: ../crates.md |