Getting Started
Cargo, the edition trap, and let being immutable by default.
Rust is a project, not a file.
cargo new and cargo run
One command makes a buildable project:
cargo new helloThree files. The manifest already names an edition:
[package]
name = "hello"
version = "0.1.0"
edition = "2024"
[dependencies]cargo run compiles and runs:
cargo runfn main and println!
The entry point, and a macro:
fn main() {
println!("Hello from Rust");
}println! is a macro, not a function. Drop the ! and nothing resolves:
fn main() {
println("no bang");
}Macros and functions live in separate namespaces, hence “in another namespace”.
Editions
An edition is an opt-in language version. This compiles on 2015:
fn main() {
let async = 5;
println!("{async}");
}The same file on edition 2024 does not:
fn main() {
let async = 5;
println!("{async}");
}async became a keyword, so an old variable name stops being legal.
Editions let Rust change the language without breaking old crates. One compiler builds all four: 2015, 2018, 2021, 2024.
Format strings
{} takes the next argument; a name inside the braces reads that variable:
fn main() {
let name = "ada";
let n = 42;
println!("{}", name);
println!("{name}");
println!("{n} and {name}");
}{:?} is the debug form, showing the value with its quotes:
fn main() {
let name = "ada";
println!("{}", name);
println!("{:?}", name);
}{:#?} indents it. The bracketed pair is chapter 2:
fn main() {
let pair = (1, "ada");
println!("{:?}", pair);
println!("{:#?}", pair);
}{} for people, {:?} for debugging. Chapter 6 opts your own types in.
Width, precision and radix go after a colon:
fn main() {
println!("{:>8}|", "ada");
println!("{:08.3}", 3.14159);
println!("{:x} {:b} {:o}", 255, 5, 8);
}let is immutable
let binds once. Assigning again is a compile error, not a convention:
fn main() {
let x = 5;
x = 6;
println!("{x}");
}The compiler names the fix. mut makes the intent explicit:
fn main() {
let mut x = 5;
let first = x;
x = 6;
println!("{first} then {x}");
}Unused is a warning
An unused variable warns and the build still succeeds:
fn main() {
let unused = 5;
println!("built anyway");
}The binary runs:
fn main() {
let _unused = 5;
println!("built anyway");
}cargo fmt and cargo clippy
Formatting is not a discussion. cargo fmt --check prints a diff and fails:
cargo fmt --checkcargo clippy teaches. It reads working code and says what a Rust programmer writes instead:
cargo clippyThat is the loop you arrive with from C, Java or Go. The suggestion is chapter 11’s.
cargo check
cargo check type-checks without building a binary:
cargo checkWith 175 dependencies and both caches warm: 0.09s against 0.14s. The saving is code generation.
| Command | Does |
|---|---|
cargo check |
Type-checks only |
cargo build |
Produces target/debug/<name> |
cargo run |
Builds, then runs it |
cargo build --release |
Optimised, and chapter 2 shows why that changes behaviour |