Rust chapters

Chapter 5 of 17

Data Types

Try this in our Rust Compiler →

Built-in types

Every value in Rust has a type that tells the computer what kind of data it is and what you can do with it. The core built-in types you will use every day are numbers, text (strings), booleans (true / false) and a "nothing here" value used for missing data.

let n: i32 = 42;
let f: f64 = 3.14;
let b: bool = true;
let s: &str = "hello";
let arr: [i32; 3] = [1, 2, 3];

Why types matter

Types stop you from making nonsense operations like multiplying a name by a date. In statically typed languages the compiler checks types before the program runs; in dynamically typed languages the check happens while the program runs. Either way you should always know roughly which type each variable holds.

Converting between types

Real programs constantly convert between types: text from a form becomes a number, a number becomes formatted text on a screen. Rust provides built-in conversion helpers — use them explicitly rather than relying on implicit conversions which can produce surprising results.

Details for rust

Bindings are immutable unless mut. Another let can shadow a name with a different type. Ownership controls dropping; borrowing allows temporary access. String owns UTF-8 text; &str borrows it. Byte count differs from character count.

Practice and verify

Change one meaningful value in the example and predict the result before running. Then test a boundary or empty value. Explain what changed and why, rather than only copying the output.

Try it yourself

Output
Run your project to see output here.
Ctrl/Cmd+Enter runs · Ctrl/Cmd+S downloads the project · Local auto-save is always on