Data Types
Explore Rust's scalar and compound data types, from integers to tuples and arrays
Learning Objectives
- map[Understand Scalar types:integers, floats, booleans, and characters]
- map[Work with Compound types:tuples and arrays]
- Learn about type inference and explicit annotation
Strong and Static
Every value in Rust is of a certain data type. Since Rust is statically typed, it must know the types of all variables at compile time.
Usually, the compiler can infer the type based on the value. But sometimes, we need to provide a type annotation:
|
|
Scalar Types
A scalar type represents a single value. Rust has four primary scalar types.
1. Integers
Integers are numbers without fractional components.
| Length | Signed | Unsigned |
|---|---|---|
| 8-bit | i8 |
u8 |
| 16-bit | i16 |
u16 |
| 32-bit | i32 |
u32 |
| 64-bit | i64 |
u64 |
| 128-bit | i128 |
u128 |
| arch | isize |
usize |
- Signed (
i): Can be positive or negative. - Unsigned (
u): Only positive. - arch: Depends on the computer’s architecture (64-bit or 32-bit).
i32.2. Floating-Point
Numbers with decimal points. Rust has two: f32 and f64 (default).
|
|
3. Boolean
true and false. Booleans are 1 byte in size.
|
|
4. Character
The char type represents a single Unicode scalar value. Note: we use single quotes for chars and double quotes for strings.
|
|
Compound Types
Compound types can group multiple values into one type.
1. The Tuple
A tuple is a way of grouping together a number of values with a variety of types into one compound type. Tuples have a fixed length.
|
|
2. The Array
Unlike a tuple, every element of an array must have the same type. Arrays in Rust have a fixed length (if you need a list that grows, use a Vector—which we’ll cover later).
|
|
Summary
Today you learned:
- Scalar types: i32, f64, bool, char.
- Compound types: Tuples (different types) and Arrays (same types, fixed length).
- How to access tuple elements (
.0) and array elements ([0]).
Practice Exercise
- Create a tuple that holds your name (string), age (integer), and height (float).
- Create an array of 5 integers and print the 3rd element.
- What happens if you try to access an index outside the array’s range (e.g.,
a[10])? Try it!
Next Steps
Tomorrow, we’ll learn about Functions—how to organize code into reusable blocks and handle return values!
Quiz
Complete this quiz with a minimum score of 80% to mark Day 3 as complete.
Discussion
Have questions or want to discuss this lesson? Join the conversation below!