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:
i32can be negative (like a temperature).u32can'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
floorof typei32with the value-2.Create
yearof typeu32with the value2024.Print
Floor -2 in 2024using 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_populationof typei64with the value8_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) andheight(3.0), both of typef64.Print
Area: 7.5by multiplyingwidth * heightinsideprintln!.
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_rainingof typebool, set tofalse.Create
gradeof typechar, set to'A'.Print
Raining: false, grade: Ausing 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
Stringis text your program owns and can grow. Make one withString::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
cityof type&strholding"Paris".Create
countryas aStringholding"France".Print
Paris is in Franceusing both variables.
Put it together: a profile card
Use four different types to describe a person, then print them all in one line.
Create
nameas aStringholding"Ada",ageas au32(36) andheightas anf64(1.65).Create
likes_rustas aboolset totrue.Print
Ada, 36, 1.65 m, likes Rust: trueusing all four variables.