Skip to content
Sign inGet all access
Chapter 2·30 minFree

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>());
}
Outputi32 max 2147483647u8 max 255u8::MIN 0sizes: i32=4 u8=1 usize=8
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);
}
Outputusize = 8 bytes, same as a pointerusize::MAX = 18446744073709551615

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}");
}
Outputf32 4 bytes, 6 digitsf64 8 bytes, 15 digitsf32 0.1 = 0.10000000149011612f64 0.1 = 0.10000000000000001f32 cannot hold 16777217: 16777216

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);
}
Outputf64 is 8 bytes0.1 + 0.2 = 0.30000000000000004equal to 0.3? falsewithin tolerance? true

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());
}
Output7.0 / 2.0 = 3.51.0 / 0.0 = inf0.0 / 0.0 is NaN: true

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());
}
Outputbool 1 byte, char 4 bytesA is 65🦀 is 129408is_alphabetic true

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);
}
Output7 / 2 = 3-7 / 2 = -37 % 2 = 1-7 % 2 = -12 + 3 * 4 = 14

Comparison and logic

The comparisons return bool, and there is no truthiness:

fn main() {
    if 1 { println!("truthy"); }
}
Output$ cargo builderror[E0308]: mismatched types --> main.rs:2:8 |2 | if 1 { println!("truthy"); } | ^ expected `bool`, found integer

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}");
}
Outputno panic, count = 0

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);
}
Output6 & 3 = 26 | 3 = 76 ^ 3 = 51 << 4 = 1616 >> 2 = 4

! does both jobs, decided by the type:

fn main() {
    println!("!true = {}", !true);
    println!("!0u8  = {}", !0u8);
}
Output!true = false!0u8 = 255

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}");
}
Output16

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);
}
Output$ cargo builderror[E0308]: mismatched types --> main.rs:4:24 |4 | println!("{}", a + b); | ^ expected `i32`, found `i64`

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}");
}
Output$ cargo builderror: this arithmetic operation will overflow --> main.rs:3:13 |3 | let b = a + 1; | ^^^^^ attempt to compute `u8::MAX + 1_u8`, which would overflow | = note: `#[deny(arithmetic_overflow)]` on by default

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}");
}
Outputthread 'main' panicked at main.rs:5:5:attempt to add with overflownote: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

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}");
}
Output0

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));
}
Outputchecked_add Nonewrapping_add 0saturating_add 255overflowing_add (0, true)
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);
}
Output300i32 as u8 = 44-1i32 as u8 = 255-1i32 as u32 = 4294967295200u8 as i32 = 200

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);
}
Output65u8 as char = A'A' as u32 = 65

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);
}
Output3.9 as i32 = 3-3.9 as i32 = -31e10 as i32 = 2147483647NaN as i32 = 0

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}");
}
Outputi64::from(42i32) = 42into i64 = 42

Ask for the lossy direction and there is no such function:

fn main() {
    let x = u8::from(300_i32);
    println!("{x}");
}
Output$ cargo builderror[E0277]: the trait bound `u8: From<i32>` is not satisfied --> main.rs:2:13 | 2 | let x = u8::from(300_i32); | ^^ the trait `From<i32>` is not implemented for `u8`

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));
}
Outputtry_from(200) = Ok(200)try_from(300) = Err(TryFromIntError(PosOverflow))try_from(-1) = Err(TryFromIntError(NegOverflow))

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));
}
Outputto_string: 42format!: 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());
}
Outputannotated: 42turbofish: 42as f64: 3.5

Without either, the compiler cannot pick:

fn main() {
    let n = "42".parse();
    println!("{:?}", n);
}
Output$ cargo builderror[E0284]: type annotations needed for `Result<_, _>` --> main.rs:2:9 | 2 | let n = "42".parse(); | ^ ----- type must be known at this point

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>());
}
Outputbad input: Err(ParseIntError { kind: InvalidDigit })with space: Err(ParseIntError { kind: InvalidDigit })

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}");
}
Outputby position: 1 adadestructured: 1 ada

.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);
}
Output[10, 20, 30] len 3first 10typed [1, 2]repeated [0, 0, 0, 0]

[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}");
}
Outputconst 3static hello

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}");
}
Outputshadowed: 12now a number: 3