Rust basics

What you learned

Course index
PDF

In PHP

A variable can change type, a string is one type, and an array is both a list and a map that keeps insertion order. match throws UnhandledMatchError when a value has no arm and that line runs. 7 / 2 is 3.5. "0" and [] are falsy. ?? fills in a missing value.

In Rust

let is immutable until you say mut. A shadow in an inner block ends when the block ends, and the outer name comes back. const is an item, not a let.

Integers default to i32, floats to f64. 7 / 2 is 3. as truncates. try_into returns Err when the value does not fit. bool has no truthiness. char is one Unicode scalar.

A function's last expression, with no semicolon, is the return value. A semicolon makes that value ().

if needs a bool and both branches share a type. (1..=5).rev() counts down. 5..1 is empty. break 'outer leaves the labelled loop.

A tuple packs mixed types. [T; N] fixes the length, and a constant index past the end does not compile. A Vec grows. v.get(i) is Option. A HashMap does not keep insertion order. A BTreeMap prints keys in sorted order.

String owns text. &str is a borrowed view. On héllo, .len() is bytes and .chars().count() is characters.

match is exhaustive at compile time. A guard is if after the pattern. let Some(x) = opt else { return; } leaves on None. The input classifier puts those pieces on a Vec<Option<i32>>.

Key takeaways

  • Names, numbers, functions, and control flow are the first half.
  • Tuples, arrays, Vec, HashMap, and strings are the collections.
  • match, Option, and the classifier are the last piece. The quiz is the button on this page.

Take the chapter quiz from the button on this page. It opens a separate page. Twelve questions, and you need 80% to pass. After you submit, each question shows a one-line explanation.

What's next: Why ownership

Download this entire chapter as one PDF (all sections in order).

Full chapter PDF

Exercises

Log in to submit exercises and track progress.

  • QuizrustRequired

    Rust basics quiz. 12 questions. You need 80% to pass.