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:
| Type | What it holds | Example |
|---|---|---|
i32 | whole numbers, positive or negative | -7, 42 |
u32 | whole numbers, zero or positive | 0, 365 |
f64 | numbers with a decimal point | 3.5, -0.25 |
bool | true or false | true |
char | a single character | 'A', '7', '😊' |
&str | a 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);
}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);
}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
- Create one variable of each type in the table and print them all.
- Store the number of seconds in a day in a
u32and print it. - Try
let small: u8 = 300;and read what the compiler says about the range of au8.