Data Types

Programming Languages · Rust Basics · 12 min

Meet Rust's everyday types: whole numbers, decimals, true/false, single characters and text.

Whole numbers: i32 and u32

Every value in Rust has a type. Two common ones for whole numbers:

  • i32 can be negative (like a temperature).
  • u32 can't (u means unsigned, no minus sign).

Write the type after a colon:

let temp: i32 = -5;

Rust can usually guess the type, so the colon part is optional. Writing it makes your intent clear.

  • Create floor of type i32 with the value -2.

  • Create year of type u32 with the value 2024.

  • Print Floor -2 in 2024 using both variables.

Big numbers: i64

An i32 only goes up to about 2 billion. For bigger numbers, use i64, which goes up to about 9 quintillion.

You can put _ inside a number to make it easier to read. Rust ignores it:

let stars: i64 = 5_000_000_000;
  • Create world_population of type i64 with the value 8_000_000_000.

  • Print world_population.

Decimals: f64

Numbers with a decimal point have the type f64. Always write the dot, even for round numbers: 3.0, not 3.

let price: f64 = 2.5;

Rust won't mix f64 and i32 in one sum, so keep your decimals together.

  • Create width (2.5) and height (3.0), both of type f64.

  • Print Area: 7.5 by multiplying width * height inside println!.

bool and char

A bool is either true or false. Perfect for yes/no questions.

A char is a single character, in single quotes:

let is_open: bool = true;
let first_letter: char = 'R';
  • Create is_raining of type bool, set to false.

  • Create grade of type char, set to 'A'.

  • Print Raining: false, grade: A using both variables.

Text: &str and String

Rust has two kinds of text:

  • "hello" written straight in your code is a &str: fixed text you can read.
  • A String is text your program owns and can grow. Make one with String::from.
let a: &str = "hi";
let b: String = String::from("hi");

Don't worry about the difference yet. It'll make sense in the ownership lesson.

  • Create city of type &str holding "Paris".

  • Create country as a String holding "France".

  • Print Paris is in France using both variables.

Put it together: a profile card

Use four different types to describe a person, then print them all in one line.

  • Create name as a String holding "Ada", age as a u32 (36) and height as an f64 (1.65).

  • Create likes_rust as a bool set to true.

  • Print Ada, 36, 1.65 m, likes Rust: true using all four variables.

More in Rust Basics

Previous: Variables · Next: Functions