Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 132 ยท Variables and Types

Integers, Floats, bool and char

A complete guide to Rust's scalar types - i8 to i128, u8 to u128, isize and usize, number literals, f32 and f64, bool and char as a 4-byte Unicode scalar value, MIN, MAX and size_of.

Rust is statically typed: every value has a type known at compile time, and the compiler checks that you combine types correctly. The simplest types are the scalar types, which hold one single value. Rust has four kinds of them: integers, floating-point numbers, booleans and characters.

This lesson covers all four in depth. Rust gives you many integer sizes and does not convert between them behind your back, which feels strict if you come from JavaScript or Python, but it prevents whole families of bugs, from silent truncation to surprising overflow. We look at what each type can hold, how to write literals, how floats really behave, why char is four bytes, and how to measure sizes with size_of. How arithmetic can overflow is the topic of the next lesson, Integer Overflow and Arithmetic, and converting between types is in Type Conversion and Casting.

Integer types

An integer is a whole number. Rust offers signed integers (which can be negative, prefix i) and unsigned integers (zero and above, prefix u) in several widths:

Length Signed Unsigned
8 bits i8 u8
16 bits i16 u16
32 bits i32 u32
64 bits i64 u64
128 bits i128 u128
pointer-sized isize usize

The number in the name is the number of bits. A signed type with n bits holds the range from -2^(n-1) to 2^(n-1) - 1, and an unsigned type from 0 to 2^n - 1. Instead of memorizing those, ask the type itself with the constants MIN, MAX and BITS:

Rust Ranges of the integer types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The last line shows that on our server usize is 64 bits, because the server is a 64-bit machine. On a 32-bit device, usize::BITS would be 32.

Which integer should I use?

  • i32 is the default. If you write let n = 5; and nothing else constrains it, n is an i32. It is a good general choice and fast on every CPU.
  • usize is for sizes and indices: the length of a vector, a position in an array, a count of things in memory. Indexing a vector requires usize, and Vec::len() returns it. It is as big as a memory address, so it can index everything the machine can hold.
  • u8 is a byte: file contents, network data, ASCII text. A [u8] slice or Vec<u8> is the standard "raw bytes" type.
  • u32/u64/i64 when you need a bigger range or a specific format: timestamps, file sizes, IDs, hash values.
  • i128/u128 for very large values, such as exact factorials or 128-bit identifiers. They are slower, since CPUs have no native 128-bit arithmetic.
  • isize is rarely needed: it appears mostly for pointer offsets.

Avoid using a signed type "just in case" for something that cannot be negative, such as a length. Using usize or u32 states the rule in the type. On the other hand, unsigned arithmetic has a trap: a - b with a < b underflows. We cover this in overflow.

Indexing needs usize

Rust will not convert for you, not even between integer sizes. A famous example: you cannot index a vector with an i32:

Rust Index with i32 (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The compiler says error[E0277]: the type `[{integer}]` cannot be indexed by `i32` and explains: slice indices are of type `usize` or ranges of `usize` . The fix is to make the variable a usize from the start (let position: usize = 1;), or convert explicitly, which is what the conversion lesson shows.

The same strictness applies to arithmetic. Adding an i32 and an i64 is an error, even though no information would be lost:

Rust Mixing integer types (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

You see error[E0308]: mismatched types (expected i32, found i64) and then error[E0277]: cannot add `i64` to `i32` . Fix it by widening explicitly: i64::from(small) + large. The rule that both operands of + have the same type may seem pedantic at first, but it is what stops a hidden i16-to-i8 truncation in a bug report six months from now.

Number literals

You can write integer literals in several ways, and the underscore is allowed anywhere inside a number so that you can group digits:

Rust Writing integer and float literals

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The output is 98222 255 63 240 65 1000000 42 1000 2.5. Note that 1e3 prints as 1000: floats print without a decimal point if the value is whole. Hex literals begin with 0x, octal with 0o, binary with 0b, and a byte literal looks like b'A' (type u8). In println!, {:x}, {:X}, {:o} and {:b} print in lowercase hex, uppercase hex, octal and binary; # adds the prefix and 08 pads with zeros to eight digits. All formatting options are covered in Printing.

If a literal does not fit into its type, Rust refuses to compile instead of wrapping:

Rust A literal that does not fit (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The error is error: literal out of range for `u8` with the note that the literal `256` does not fit into the type `u8` whose range is `0..=255` . This check is a deny-by-default lint named overflowing_literals.

Floating-point types

Rust has two float types: f32 (single precision, 32 bits) and f64 (double precision, 64 bits). Both follow the IEEE 754 standard, like the numbers in almost every language and on every CPU. The default is f64, because on modern CPUs it is about as fast as f32 and far more precise. Use f32 when memory or bandwidth matters (graphics, big arrays, machine learning weights).

The most important thing to know about floats is that most decimal fractions cannot be stored exactly in binary:

Rust Floats are approximations

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Step through the output:

  • 0.1 + 0.2 prints 0.30000000000000004, and comparing it to 0.3 with == is false. This is not a Rust quirk; it is binary floating point. Never compare floats with == after arithmetic. Compare within a tolerance, such as (a - b).abs() < 1e-9, or use f64::EPSILON scaled to the size of your numbers.
  • {:.2} rounds only for display; the stored value is unchanged.
  • 7.0 / 2.0 is 3.5, but 7 / 2 with integers is 3: integer division truncates.
  • {:e} prints scientific notation. f64::EPSILON (about 2.2e-16) is the gap between 1.0 and the next float, not "the smallest float".
  • Dividing by zero with floats does not panic. It gives infinity (inf, -inf), and 0.0 / 0.0 is NaN ("not a number"). NaN is not equal to anything, including itself, so test it with is_nan(). The next lesson has a section on NaN.
  • round() rounds half away from zero (2.5 becomes 3), floor and ceil go down and up, trunc cuts the fraction.
  • A float prints as 1.0 with the Debug format {:?} and as 1 with the Display format {}. 16_777_217_f32 prints as 16777216: an f32 has only 24 bits of precision, so it cannot represent this integer.

You must write the type or a decimal point to get a float: let x = 2; is an integer, let y = 2.0; is an f64. And you cannot mix them: 2 * 1.5 fails to compile, because an integer and a float are different types.

Because of NaN, floats do not implement Ord or Eq. You cannot call .sort() on a Vec<f64> or use a float as a HashMap key. Use sort_by with partial_cmp or total_cmp; see Sorting, Searching and Comparison.

bool

The type bool has exactly two values, true and false. It is the result of comparisons (3 > 2) and the only type accepted by if and while conditions, which means Rust has no "truthy" values: if 1 { ... } and if some_string { ... } do not compile.

Rust Booleans and their operators

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

&& and || are short-circuiting: a && b does not evaluate b when a is false. The single-character forms &, | and ^ also work on bools but always evaluate both sides. A bool occupies one byte, not one bit, because every value needs a unique address. Only true and false are valid bit patterns; the compiler uses the other 254 patterns of that byte for tricks such as making Option<bool> also one byte.

The method then_some(value) turns a bool into an Option: Some(value) if true, None if false. Its sibling then(|| ...) takes a closure that only runs when the condition holds, which is better when computing the value is expensive.

char

A char is not a byte and not a "character" in the everyday sense. It is a Unicode scalar value: any code point from U+0000 to U+10FFFF, except the surrogate range U+D800 to U+DFFF. In memory it always takes 4 bytes. You write it in single quotes (strings use double quotes):

Rust char holds any Unicode scalar value

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

What this shows:

  • A char can be a letter from any alphabet, a symbol or an emoji, but each char is one scalar value, which may still not be what a human sees as one character. The family emoji or "รฉ" written as e plus an accent are several chars. Perceived characters ("grapheme clusters") need an external crate.
  • size_of::<char>() is 4, while the UTF-8 encoded length ranges from 1 to 4 bytes (len_utf8). Strings are stored as UTF-8 and so "hรฉllo" has 6 bytes but 5 chars. String and &str Basics builds on this.
  • as u32 gives the code point, and '\u{1F980}' writes a char by code point. Escapes use a backslash: \n, \t, \', \\, \u{...}.
  • Methods such as is_alphabetic, is_numeric and to_uppercase are Unicode-aware. 'รŸ'.to_uppercase() yields an iterator that prints as SS: one lowercase char can become several uppercase ones. to_ascii_uppercase is the simple 1:1 version.
  • to_digit(radix) returns an Option<u32>; char::from_digit and char::from_u32 return Option<char>, because not every number is a valid char (the surrogate 0xD800 is not, so you get None).

Measuring sizes with size_of

std::mem::size_of::<T>() returns the size of a type in bytes at compile time. It is a quick way to build intuition for memory:

Rust size_of for the scalar types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Some observations. The sizes of the integers match their names (i32 is 4 bytes). The unit type () takes 0 bytes: it carries no information. A &str is 16 bytes on a 64-bit machine, because it is a fat pointer made of an address and a length. Option<u32> needs 8 bytes (4 for the number and a tag, padded), but Option<&u32> fits in 8 bytes, the same as a plain reference: Rust knows a reference is never null, so it uses the null address to mean None. This trick is called a niche optimization and is part of why Rust's abstractions are cheap. An array of 5 u16s takes exactly 10 bytes. There is more in Memory Layout.

Handy integer methods

Integers come with many useful methods, so you rarely need to write bit tricks yourself:

Rust A tour of integer methods

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

You will use pow, abs, min, max, clamp and from_str_radix (parse in any base from 2 to 36) all the time. isqrt (integer square root) is stable since Rust 1.84. The checked_, wrapping_, saturating_ and overflowing_ families are in the next lesson.

Common mistakes

  • Using usize for values that can be negative, or i32 for lengths, and then fighting conversions everywhere.
  • Comparing floats with == after any calculation.
  • Expecting 7 / 2 to be 3.5. Both operands are integers, so the result is 3.
  • Treating char as one byte or len() of a string as the number of characters.
  • Using f32 by default. Its 24-bit precision loses integers above 16,777,216.
  • Writing a literal outside the range of the annotated type; the compiler rejects it.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the type of n in let n = 5; when nothing else constrains it?

    Integer literals default to i32 and decimal literals default to f64. Other uses of the variable can change the inferred type.
  2. 2. Why does let v = vec![1, 2, 3]; let i: i32 = 0; v[i] not compile?

    Slices and vectors are indexed by usize or ranges of usize. Rust never converts integer types implicitly, so you must use a usize or convert explicitly.
  3. 3. How many bytes does a char take in memory?

    A char is a Unicode scalar value and always uses 4 bytes in memory. Its UTF-8 encoding in a string, however, takes 1 to 4 bytes.
  4. 4. What does 0.1 + 0.2 == 0.3 evaluate to for f64 values?

    0.1 + 0.2 is 0.30000000000000004 in binary floating point. Compare floats with a tolerance instead of ==.
  5. 5. What is 7 / 2 when both numbers are integer literals?

    Integer division truncates toward zero, so the result is 3. Write 7.0 / 2.0 for 3.5.

Summary

  • Rust has signed (i8 to i128, isize) and unsigned (u8 to u128, usize) integers; i32 is the default and usize is used for sizes and indices.
  • MIN, MAX, BITS and size_of tell you the facts instead of memorization.
  • Literals may use _, the prefixes 0x, 0o, 0b, byte literals b'A', and type suffixes such as 42u8; out-of-range literals are compile errors.
  • Rust never converts between numeric types implicitly, not even i32 to i64.
  • f64 (default) and f32 follow IEEE 754: inexact decimals, inf, and NaN that is not equal to itself; compare with tolerance.
  • bool is true or false and the only valid condition type; && and || short-circuit.
  • char is a 4-byte Unicode scalar value written in single quotes; strings are UTF-8, so bytes, chars and perceived characters differ.

Next: Integer Overflow and Arithmetic shows what happens when a calculation leaves the range of its type.