5.6 Numeric Literals
Rust requires each numeric literal to have a well-defined type at compile time, determined either by the context or an explicit suffix.
5.6.1 Integer Literals
By default, integer literals are i32
. You can add a type suffix (e.g., 123u16
) to specify another type. Underscores (_
) improve readability:
#![allow(unused)] fn main() { let large = 1_000_000; // 1 million, i32 }
5.6.2 Floating-Point Literals
By default, floating-point literals are interpreted as f64
. If you want f32
, you can add an explicit suffix, like 3.14f32
. Rust requires at least one digit before the decimal point, so 0.7
is valid but .7
is not. It also permits writing a trailing decimal point with no digits after it, so 1.
is valid (and means the same as 1.0
).
5.6.3 Hex, Octal, and Binary
Rust supports integer literals in multiple bases: hexadecimal (0x
), octal (0o
), and binary (0b
). Although decimal and hexadecimal literals are most common, octal literals can still be useful for specifying file permissions in Unix-like systems or interacting with certain hardware. You can also create a byte literal using b'X'
, which produces a u8
corresponding to the ASCII code of X
.
fn main() { let hex = 0xFF; // 255 in decimal let oct = 0o377; // 255 in decimal let bin = 0b1111_1111; // 255 in decimal let byte = b'A'; // 65 in decimal (ASCII for 'A') println!("{} {} {} {}", hex, oct, bin, byte); }
5.6.4 Type Inference
Context determines how Rust interprets numeric literals. For instance, if you assign 42
to a floating-point variable, you must either write 42.0
or cast it (e.g., 42 as f64
).