Numbers
| Integers with suffixes | |
| Floats | |
| Basic math | |
| Cast with as |
Integers with suffixes
Integer types name a size and a sign, such as u8 for small unsigned values and i64 for large signed ones.
A suffix on the literal picks the type directly when the default i32 is not wanted.
fn main() {
let small = 42u8;
let big: i64 = 1000000;
println!("{} {}", small, big);
}
cargo run
42 1000000
Floats
Decimal numbers default to f64, which fits most calculations.
Use f32 only when memory or an external format calls for the smaller size.
fn main() {
let pi = 3.14;
let exact: f64 = 2.0;
println!("{} {}", pi, exact);
}
cargo run
3.14 2
Basic math
The usual operators cover addition, subtraction, multiplication, division, and remainder.
Integer division drops the fraction, so 7 divided by 2 gives 3.
fn main() {
let sum = 7 + 2;
let diff = 7 - 2;
let prod = 7 * 2;
let div = 7 / 2;
println!("{} {} {} {}", sum, diff, prod, div);
}
cargo run
9 5 14 3
Cast with as
Rust never converts numbers silently, so casts stay explicit with the as keyword.
Float to integer casts drop the fraction part.
fn main() {
let a = 200u16;
let b = a as u8;
let c = 9.7;
let d = c as i32;
println!("{} {}", b, d);
}
cargo run
200 9
Next: Strings
Article author: Arthur Isaev