Based on the book by Steve Klabnik and Carol Nichols
- Cargo and Package Management
- Programming a Guessing Game
- Common Programming Concepts
- Understanding Ownership
- Using Structs to Structure Related Data
- Enums and Pattern Matching
1. Cargo and Package Management
What is Cargo?
Cargo is Rust’s built-in build system and package manager that handles:
- Building your code
- Managing dependencies
- Running tests
- Generating documentation
Key Files
Cargo.toml: Configuration file written in TOML (Tom’s Obvious Minimal Language)[package]section: Configures package metadata[dependencies]section: Lists external dependencies
Cargo.lock: Automatically generated file that tracks exact versions of dependencies for reproducible builds
Essential Cargo Commands
cargo new # Create a new project
cargo build # Compile the project
cargo run # Compile and run the project
cargo check # Check if code compiles without producing binary
cargo build --release # Build optimized release version
cargo update # Update dependencies (ignores lock file)
cargo doc --open # Generate and open documentation
Package Registry
- crates.io: The official Rust package registry where all public crates are stored
- Semantic Versioning (SemVer): Version format like
0.8.5means compatible with0.8.xbut not0.9.x
2. Programming a Guessing Game
This chapter introduces basic Rust concepts through building a number guessing game.
Key Concepts Introduced
Input/Output Operations
use std::io; // Import standard library's io module
fn main() {
println!("Guess the number!"); // Print macro
let mut guess = String::new(); // Mutable variable
io::stdin()
.read_line(&mut guess) // Read user input
.expect("Failed to read line");
}
Important Syntax Elements
use std::io;: Brings the io module into scope::: Associated function syntax (like static methods)&mut: Mutable reference//: Single-line commentprintln!(): Macro for printing (note the!)
String Type
String: Growable, UTF-8 encoded text type stored on the heapString::new(): Associated function that creates a new empty string
References
&: Creates a reference (allows multiple parts of code to access data without copying)- References are immutable by default
&mut: Creates a mutable reference
Error Handling with Result
enum Result<T, E> {
Ok(T), // Operation succeeded, contains the value
Err(E), // Operation failed, contains error information
}
Resultis an enum with two variants:OkandErr.expect(): Method that crashes the program with a custom message if Result isErr
Pattern Matching
use std::cmp::Ordering;
match guess.cmp(&secret_number) {
Ordering::Less => println!("Too small!"),
Ordering::Greater => println!("Too big!"),
Ordering::Equal => println!("You win!"),
}
String Methods
.trim(): Removes whitespace from beginning and end.parse(): Converts string to another type
Loops and Control Flow
loop {
// Infinite loop
if condition {
break; // Exit the loop
}
}
3. Common Programming Concepts
Variables and Mutability
Variable Declarations
let x = 5; // Immutable variable (default)
let mut y = 5; // Mutable variable
const MAX_POINTS: u32 = 100_000; // Constant (always immutable)
Key Differences
- Variables: Immutable by default, can be made mutable with
mut - Constants: Always immutable, type must be annotated, named in SCREAMING_SNAKE_CASE
- Shadowing: Allows reusing variable names with
let, even changing types
Data Types
Rust is statically typed - all variable types must be known at compile time.
Scalar Types (Single Values)
1. Integer Types
| 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: Can store negative numbers, range:
-(2^(n-1))to2^(n-1) - 1 - Unsigned: Only positive numbers, range:
0to2^n - 1 - Default:
i32 - arch types: Size depends on architecture (64-bit on 64-bit systems)
Integer Literals
let decimal = 98_222;
let hex = 0xff;
let octal = 0o77;
let binary = 0b1111_0000;
let byte = b'A'; // u8 only
Integer Overflow
- Debug mode: Rust panics on integer overflow
- Release mode: Wraps around using two’s complement
2. Floating Point Types
let x = 2.0; // f64 (default)
let y: f32 = 3.0; // f32
- f32: Single precision (32-bit)
- f64: Double precision (64-bit, default)
- Follows IEEE 754 standard
3. Boolean Type
let t = true;
let f: bool = false; // 1 byte in size
4. Character Type
let c = 'z';
let heart_eyed_cat = '😻';
- 4 bytes in size
- Represents Unicode Scalar Values
Compound Types
1. Tuples
let tup: (i32, f64, u8) = (500, 6.4, 1);
let (x, y, z) = tup; // Destructuring
let first = tup.0; // Access by index
- Fixed length once declared
- Can contain different types
- Access elements with
.0,.1, etc.
2. Arrays
let a = [1, 2, 3, 4, 5];
let a: [i32; 5] = [1, 2, 3, 4, 5]; // Type annotation
let a = [3; 5]; // [3, 3, 3, 3, 3]
let first = a[0]; // Index access
- Fixed length
- Same type for all elements
- Stored on stack (not heap)
- Bounds checking at runtime - panics on invalid access
Functions
fn main() {
println!("Hello, world!");
another_function(5);
}
fn another_function(x: i32) {
println!("The value of x is: {}", x);
}
Key Points
- Entry point:
mainfunction - Naming: snake_case convention
- Parameters: Must declare type for each parameter
- Body: Made up of statements and expressions
Statements vs Expressions
- Statements: Instructions that perform actions, don’t return values
- Expressions: Evaluate to a value
- Note:
let x = y = 6;is invalid in Rust (unlike other languages)
Return Values
fn five() -> i32 {
5 // Expression (no semicolon)
}
fn plus_one(x: i32) -> i32 {
x + 1 // Expression returns value
}
- Return type: Declared after
->arrow - Early return: Use
returnkeyword - Default return: Last expression without semicolon
Control Flow
If Expressions
if number < 5 {
println!("condition was true");
} else if number == 6 {
println!("number was six");
} else {
println!("condition was false");
}
let number = if condition { 5 } else { 6 }; // If is an expression
Loops
1. loop - Infinite Loop
loop {
println!("again!");
if condition {
break;
}
}
let result = loop {
counter += 1;
if counter == 10 {
break counter * 2; // Return value from loop
}
};
2. Loop Labels
'counting_up: loop {
loop {
break 'counting_up; // Break outer loop
}
}
3. while Loops
while number != 0 {
println!("{}", number);
number -= 1;
}
4. for Loops
let a = [10, 20, 30, 40, 50];
for element in a {
println!("the value is: {}", element);
}
for number in (1..4).rev() { // Range with reverse
println!("{}!", number);
}
4. Understanding Ownership
Ownership is Rust’s unique approach to memory management without a garbage collector.
Memory Management Approaches
- Garbage Collection: Language automatically finds and cleans unused memory
- Manual Management: Programmer explicitly allocates/frees memory
- Ownership System: Rust’s approach - compiler checks ownership rules at compile time
Stack vs Heap
The Stack
- LIFO (Last In, First Out) structure
- Fast access and allocation
- Fixed size data only
- Automatic cleanup when scope ends
The Heap
- Less organized than stack
- Slower access (follow pointer)
- Dynamic size data
- Manual management needed
- Allocation: Request space, get pointer back
Ownership Rules
- Each value has exactly one owner
- Only one owner at a time
- Value is dropped when owner goes out of scope
Variable Scope
{ // s is not valid here
let s = "hello"; // s is valid from this point forward
// do stuff with s
} // scope ends, s is no longer valid
String Types
let s1 = "hello"; // String literal (immutable, stack)
let s2 = String::from("hello"); // String type (mutable, heap)
s2.push_str(", world!"); // Modify heap string
Memory and Allocation
Automatic Memory Management
{
let s = String::from("hello"); // Memory allocated
// use s
} // drop() called automatically, memory freed
When a variable goes out of scope, Rust calls drop() automatically.
Move Semantics
let s1 = String::from("hello");
let s2 = s1; // s1 is moved to s2, s1 is no longer valid
// println!("{}", s1); // This would cause a compile error
Why Move Instead of Copy?
- Prevents double free errors
- String contains: pointer, length, capacity (on stack)
- Actual string data stored on heap
- Moving transfers ownership, invalidates original variable
Clone for Deep Copy
let s1 = String::from("hello");
let s2 = s1.clone(); // Deep copy, both valid
println!("{} {}", s1, s2); // Works fine
Copy Trait
let x = 5;
let y = x; // Both x and y are valid (Copy trait)
Types that implement Copy:
- All integer types
- Boolean type
- All floating point types
- Character type
- Tuples containing only Copy types
Ownership and Functions
fn main() {
let s = String::from("hello");
takes_ownership(s); // s moved into function
// s no longer valid here
let x = 5;
makes_copy(x); // x copied (i32 has Copy trait)
// x still valid here
}
fn takes_ownership(some_string: String) {
println!("{}", some_string);
} // some_string dropped here
fn makes_copy(some_integer: i32) {
println!("{}", some_integer);
} // some_integer goes out of scope, nothing special happens
References and Borrowing
Immutable References
fn main() {
let s1 = String::from("hello");
let len = calculate_length(&s1); // Borrow s1
println!("The length of '{}' is {}.", s1, len); // s1 still valid
}
fn calculate_length(s: &String) -> usize {
s.len()
} // s goes out of scope, but doesn't drop the data (it doesn't own it)
Mutable References
fn main() {
let mut s = String::from("hello");
change(&mut s);
}
fn change(some_string: &mut String) {
some_string.push_str(", world");
}
Reference Rules
- At any time: Either one mutable reference OR any number of immutable references
- References must always be valid (no dangling pointers)
- Cannot mix mutable and immutable references in same scope
let mut s = String::from("hello");
let r1 = &s; // OK
let r2 = &s; // OK
let r3 = &mut s; // ERROR! Cannot have mutable ref while immutable refs exist
The Slice Type
let s = String::from("hello world");
let hello = &s[0..5]; // Slice of first 5 characters
let world = &s[6..11]; // Slice from index 6 to 11
let whole = &s[..]; // Slice of entire string
- Slice: Reference to a contiguous sequence of elements
- No ownership: Slices are references
- String slices: Type
&str
5. Using Structs to Structure Related Data
Structs are like objects in other languages - they group related data together.
Defining and Instantiating Structs
struct User {
active: bool,
username: String,
email: String,
sign_in_count: u64,
}
let user1 = User {
active: true,
username: String::from("someusername123"),
email: String::from("someone@example.com"),
sign_in_count: 1,
};
Field Access and Mutation
let mut user1 = User { /* ... */ };
user1.email = String::from("anotheremail@example.com");
Note: Entire struct must be mutable, not individual fields.
Field Init Shorthand
fn build_user(email: String, username: String) -> User {
User {
active: true,
username, // Shorthand when parameter name matches field name
email, // Equivalent to email: email,
sign_in_count: 1,
}
}
Struct Update Syntax
let user2 = User {
email: String::from("another@example.com"),
..user1 // Use remaining fields from user1
};
Tuple Structs
struct Color(i32, i32, i32);
struct Point(i32, i32, i32);
let black = Color(0, 0, 0);
let origin = Point(0, 0, 0);
- Different types:
ColorandPointare different types even with same structure - Access: Use
.0,.1,.2like tuples
Unit-Like Structs
struct AlwaysEqual;
let subject = AlwaysEqual;
Useful for implementing traits without storing data.
Ownership in Structs
struct User {
username: String, // Owned data
email: String, // Owned data
active: bool,
sign_in_count: u64,
}
- Owned data: Struct owns all its data
- Lifetimes: Can store references, but requires lifetime annotations
Debug Trait
#[derive(Debug)]
struct Rectangle {
width: u32,
height: u32,
}
let rect = Rectangle { width: 30, height: 50 };
println!("{:?}", rect); // Debug format
println!("{:#?}", rect); // Pretty-print debug format
Methods
#[derive(Debug)]
struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
fn area(&self) -> u32 {
self.width * self.height
}
fn can_hold(&self, other: &Rectangle) -> bool {
self.width > other.width && self.height > other.height
}
fn square(size: u32) -> Rectangle { // Associated function
Rectangle {
width: size,
height: size,
}
}
}
let rect = Rectangle { width: 30, height: 50 };
println!("Area: {}", rect.area());
let square = Rectangle::square(25); // Call associated function
Method Types
- Instance methods: Take
&self,&mut self, orself - Associated functions: Don’t take
self(like static methods) - Getters: Methods with same name as field for read-only access
Automatic Referencing/Dereferencing
Rust automatically adds &, &mut, or * to match method signature:
rect.area(); // Automatically becomes (&rect).area()
6. Enums and Pattern Matching
Enums allow you to define types by enumerating possible variants.
Defining Enums
enum IpAddrKind {
V4,
V6,
}
let four = IpAddrKind::V4;
let six = IpAddrKind::V6;
Enums with Data
enum IpAddr {
V4(u8, u8, u8, u8),
V6(String),
}
let home = IpAddr::V4(127, 0, 0, 1);
let loopback = IpAddr::V6(String::from("::1"));
Complex Enum Example
enum Message {
Quit, // No data
Move { x: i32, y: i32 }, // Named fields
Write(String), // Single string
ChangeColor(i32, i32, i32), // Three integers
}
The Option Enum
enum Option<T> {
None,
Some(T),
}
let some_number = Some(5);
let some_string = Some("a string");
let absent_number: Option<i32> = None;
- Purpose: Represents a value that might be absent
- No null values: Rust doesn’t have null, uses
Optioninstead - Must handle: Forces you to handle the
Nonecase