Types, Operators and Conversions
The primitives, the operators, overflow, and every way a number changes type.
Width is part of the type, and nothing converts on its own.
Integers
Signed and unsigned, in five widths each, and the width is in the name:
fn main() {
let a: i32 = 2_147_483_647;
let b: u8 = 255;
println!("i32 max {a}");
println!("u8 max {b}");
println!("u8::MIN {}", u8::MIN);
println!("sizes: i32={} u8={} usize={}",
size_of::<i32>(), size_of::<u8>(), size_of::<usize>());
}| Signed | Unsigned | Bytes |
|---|---|---|
i8 |
u8 |
1 |
i16 |
u16 |
2 |
i32 |
u32 |
4 |
i64 |
u64 |
8 |
i128 |
u128 |
16 |
isize |
usize |
4 or 8 (pointer-sized) |
An integer with no annotation is i32. Underscores in literals are ignored.
isize and usize match the CPU’s pointer width: 4 bytes on a 32-bit target, 8 on a
64-bit one. That is why the snippet prints usize=8 here:
fn main() {
println!("usize = {} bytes, same as a pointer",
size_of::<usize>());
println!("usize::MAX = {}", usize::MAX);
}Floats
Two of them. f32 is 4 bytes, f64 is 8, and an unannotated float is f64:
fn main() {
println!("f32 {} bytes, {} digits", size_of::<f32>(), f32::DIGITS);
println!("f64 {} bytes, {} digits", size_of::<f64>(), f64::DIGITS);
let a: f32 = 0.1;
println!("f32 0.1 = {a:.17}");
println!("f64 0.1 = {:.17}", 0.1_f64);
let n: f32 = 16_777_217.0;
println!("f32 cannot hold 16777217: {n}");
}DIGITS is how many decimal digits survive a round trip: 6 against 15. The last line is the
one that bites — f32 runs out of whole numbers at 2^24.
The default f64 in more detail:
fn main() {
let x = 1.5;
println!("f64 is {} bytes", size_of_val(&x));
println!("0.1 + 0.2 = {}", 0.1 + 0.2);
println!("equal to 0.3? {}", 0.1 + 0.2 == 0.3);
println!("within tolerance? {}", (0.1 + 0.2 - 0.3_f64).abs() < 1e-10);
}Division gives a float and never panics:
fn main() {
println!("7.0 / 2.0 = {}", 7.0 / 2.0);
println!("1.0 / 0.0 = {}", 1.0_f64 / 0.0);
println!("0.0 / 0.0 is NaN: {}", (0.0_f64 / 0.0).is_nan());
}bool and char
A bool is one byte. A char is four, because it holds any Unicode scalar value:
fn main() {
let yes = true;
let c = 'A';
let crab = '🦀';
println!("bool {} byte, char {} bytes",
size_of_val(&yes), size_of_val(&c));
println!("{c} is {}", c as u32);
println!("{crab} is {}", crab as u32);
println!("is_alphabetic {}", c.is_alphabetic());
}Single quotes are a char, double quotes a string. One emoji is one char — chapter 7 shows that
is not one byte.
Arithmetic
Five operators, and integer division truncates:
fn main() {
println!("7 / 2 = {}", 7 / 2);
println!("-7 / 2 = {}", -7 / 2);
println!("7 % 2 = {}", 7 % 2);
println!("-7 % 2 = {}", -7 % 2);
println!("2 + 3 * 4 = {}", 2 + 3 * 4);
}Comparison and logic
The comparisons return bool, and there is no truthiness:
fn main() {
if 1 { println!("truthy"); }
}0, an empty string and an empty list are not false. A condition is a bool or it does not compile.
&& and || short-circuit, which is what stops the division here:
fn main() {
let mut count = 0;
let n = 0;
if n != 0 && 100 / n > 5 {
count += 1;
}
println!("no panic, count = {count}");
}100 / n with n zero panics. The left side was false, so the right never ran.
Bitwise operators
Five, and no ~:
fn main() {
println!("6 & 3 = {}", 6 & 3);
println!("6 | 3 = {}", 6 | 3);
println!("6 ^ 3 = {}", 6 ^ 3);
println!("1 << 4 = {}", 1 << 4);
println!("16 >> 2 = {}", 16 >> 2);
}! does both jobs, decided by the type:
fn main() {
println!("!true = {}", !true);
println!("!0u8 = {}", !0u8);
}Logical negation on a bool, bitwise NOT on an integer. No separate ~ to learn.
Compound assignment
+= and friends need mut, like any other change:
fn main() {
let mut n = 5;
n += 3;
n *= 2;
println!("{n}");
}There is no ++ or -- in Rust — write n += 1.
Mixed widths do not add
i32 + i64 is a compile error. There is no promotion anywhere in the language:
fn main() {
let a: i32 = 5;
let b: i64 = 10;
println!("{}", a + b);
}Operators are trait calls, from std::ops. Chapter 9 implements + for a type of its own.
Overflow
A constant that overflows will not compile:
fn main() {
let a: u8 = 255;
let b = a + 1;
println!("{b}");
}Build the same sum step by step and it reaches runtime, where debug panics:
fn main() {
let mut a: u8 = 250;
let step: u8 = 3;
a += step;
a += step;
println!("{a}");
}The same program compiled with optimisations wraps instead:
fn main() {
let mut a: u8 = 250;
let step: u8 = 3;
a += step;
a += step;
println!("{a}");
}Saying which you meant
Four methods that make the choice explicit instead of build-dependent:
fn main() {
let a: u8 = 255;
println!("checked_add {:?}", a.checked_add(1));
println!("wrapping_add {}", a.wrapping_add(1));
println!("saturating_add {}", a.saturating_add(1));
println!("overflowing_add {:?}", a.overflowing_add(1));
}| Method | On overflow |
|---|---|
checked_add |
None |
wrapping_add |
wraps around |
saturating_add |
stops at the maximum |
overflowing_add |
the wrapped value, and a flag |
as
as converts between number types. It never fails, which is the problem:
fn main() {
println!("300i32 as u8 = {}", 300_i32 as u8);
println!("-1i32 as u8 = {}", -1_i32 as u8);
println!("-1i32 as u32 = {}", -1_i32 as u32);
println!("200u8 as i32 = {}", 200_u8 as i32);
}as also converts between char and the integer types:
fn main() {
println!("65u8 as char = {}", 65_u8 as char);
println!("'A' as u32 = {}", 'A' as u32);
}as on floats
Float to integer truncates toward zero, and the edges are worth knowing:
fn main() {
println!("3.9 as i32 = {}", 3.9_f64 as i32);
println!("-3.9 as i32 = {}", -3.9_f64 as i32);
println!("1e10 as i32 = {}", 1e10_f64 as i32);
println!("NaN as i32 = {}", f64::NAN as i32);
}From and Into
From exists only where the conversion cannot lose anything:
fn main() {
let n = i64::from(42_i32);
println!("i64::from(42i32) = {n}");
let m: i64 = 42_i32.into();
println!("into i64 = {m}");
}Ask for the lossy direction and there is no such function:
fn main() {
let x = u8::from(300_i32);
println!("{x}");
}TryFrom
The answer that missing From points at. It reports failure instead of hiding it:
fn main() {
println!("try_from(200) = {:?}", u8::try_from(200_i32));
println!("try_from(300) = {:?}", u8::try_from(300_i32));
println!("try_from(-1) = {:?}", u8::try_from(-1_i32));
}Ok and Err are the two halves of Result, which chapter 8 is about. The error even says which
direction overflowed.
| Need | Use |
|---|---|
| Widening, cannot fail | From / Into |
| Narrowing, might fail | TryFrom |
| Truncation is intended | as, with a comment |
| Float to integer | as, knowing it saturates |
Numbers to strings
Two ways, and both are everywhere:
fn main() {
println!("to_string: {}", 42.to_string());
println!("format!: {}", format!("value {}", 42));
}Strings to numbers
parse needs to know what to build, so annotate the variable or use a turbofish:
fn main() {
let n: i32 = "42".parse().unwrap();
println!("annotated: {n}");
println!("turbofish: {}", "42".parse::<i32>().unwrap());
println!("as f64: {}", "3.5".parse::<f64>().unwrap());
}Without either, the compiler cannot pick:
fn main() {
let n = "42".parse();
println!("{:?}", n);
}Parsing can fail, so it returns a Result. .unwrap() above takes the value and panics otherwise —
chapter 8 does it properly:
fn main() {
println!("bad input: {:?}", "abc".parse::<i32>());
println!("with space: {:?}", " 42".parse::<i32>());
}Tuples
A fixed group of values, possibly of different types:
fn main() {
let pair = (1, "ada");
println!("by position: {} {}", pair.0, pair.1);
let (n, name) = pair;
println!("destructured: {n} {name}");
}.0 and .1 are the field names. Chapter 3 uses this pattern syntax everywhere.
Arrays
An array’s length is part of its type, so it cannot grow:
fn main() {
let nums = [10, 20, 30];
println!("{:?} len {}", nums, nums.len());
println!("first {}", nums[0]);
let typed: [u8; 2] = [1, 2];
println!("typed {:?}", typed);
let zeros = [0; 4];
println!("repeated {:?}", zeros);
}[i32; 3] and [i32; 4] are different types. For a list that grows you want Vec, in chapter 7.
const and static
Both are compile-time values, written in SCREAMING_SNAKE_CASE, and both need a type:
const MAX_RETRIES: u32 = 3;
static GREETING: &str = "hello";
fn main() {
println!("const {MAX_RETRIES}");
println!("static {GREETING}");
}const is inlined at each use; static has one fixed address. Prefer const.
Shadowing
A second let with the same name makes a new variable:
fn main() {
let x = 5;
let x = x + 1;
let x = x * 2;
println!("shadowed: {x}");
let spaces = " ";
let spaces = spaces.len();
println!("now a number: {spaces}");
}