Shiklo Tools
PDF40
Image20
Calculators & Converters25
Text & Writing13
Developer26
Video14
Audio14
Document14
Data & Spreadsheet12
Web & SEO9
OCR & Scanning5
Archive & File12
Security & Privacy23
Health & Medical29
QR & Barcode5

Rust Data Types

Every value in Rust has a type, which tells Rust what kind of thing it is and what you can do with it. You can add two numbers, but not a number and a word. Knowing the type lets the compiler check your program before it runs, and lets it store each value in exactly the right amount of memory.

Here are the basic types you will use all the time:

TypeWhat it holdsExample
i32whole numbers, positive or negative-7, 42
u32whole numbers, zero or positive0, 365
f64numbers with a decimal point3.5, -0.25
booltrue or falsetrue
chara single character'A', '7', '😊'
&stra piece of text"hello"

Rust usually guesses for you

Most of the time you do not have to write the type. Rust looks at the value and works it out, which is called type inference. A whole number becomes an i32, a number with a point becomes an f64.

fn main() {
    let count = 12;
    let height = 1.65;
    let is_raining = false;
    let grade = 'A';
    println!("{} {} {} {}", count, height, is_raining, grade);
}
Output
12 1.65 false A

Writing the type yourself

Sometimes you want a specific type, or Rust cannot guess. Then you write a colon and the type after the name. This is called a type annotation:

fn main() {
    let population: u64 = 1_400_000_000;
    let temperature: f32 = -3.5;
    let initial: char = 'R';
    println!("{} people", population);
    println!("{} degrees", temperature);
    println!("Initial: {}", initial);
}
Output
1400000000 people
-3.5 degrees
Initial: R

The underscores in 1_400_000_000 are just there to make the number easy to read, like the commas you would write on paper. Rust ignores them.

Why so many number types?

The number in a type name is the number of bits used to store it. An i8 uses 8 bits and holds values from -128 to 127, while an i64 holds numbers in the quintillions. The i types can be negative, the u types (for unsigned) cannot. If you are not sure which to pick, i32 for whole numbers and f64 for decimals are excellent defaults.

Characters use single quotes and text uses double quotes. 'a' is a char, while "a" is a piece of text that happens to be one letter long. Mixing them up is a very common first error, and now you know what the compiler means when it mentions it.

Practice exercises

  1. Create one variable of each type in the table and print them all.
  2. Store the number of seconds in a day in a u32 and print it.
  3. Try let small: u8 = 300; and read what the compiler says about the range of a u8.