Rust is known for its focus on memory safety without a garbage collector. Why is this important?
Think about common bugs in languages like C and how Rust tries to avoid them.
Rust uses a system of ownership and borrowing checked at compile time to prevent common memory bugs such as null pointer dereferencing and data races, without needing a garbage collector.
Consider this Rust code snippet:
fn main() {
let s1 = String::from("hello");
let s2 = s1;
println!("{}", s1);
}What happens when you run this code?
Think about what happens when ownership is transferred in Rust.
In Rust, assigning s1 to s2 moves ownership. After the move, s1 is no longer valid, so using s1 causes a compile-time error.
Look at this Rust code:
fn main() {
let s = String::from("hello");
let len = calculate_length(&s);
println!("Length: {}", len);
}
fn calculate_length(s: &String) -> usize {
s.len()
}What will this program print?
Borrowing allows reading data without taking ownership.
The function borrows s by reference, so ownership is not moved. The length of "hello" is 5, so it prints 'Length: 5'.
Rust is gaining popularity for system-level programming. What is the main reason?
Think about what system programming needs and how Rust addresses those needs.
Rust offers control over hardware and memory like C/C++, but adds safety and concurrency features checked at compile time, all without a garbage collector, making it ideal for system programming.
Consider this Rust code:
enum Message {
Quit,
Move { x: i32, y: i32 },
Write(String),
ChangeColor(i32, i32, i32),
}
fn process_message(msg: Message) {
match msg {
Message::Quit => println!("Quit message"),
Message::Move { x, y } => println!("Move to ({}, {})", x, y),
Message::Write(text) => println!("Text message: {}", text),
Message::ChangeColor(r, g, b) => println!("Change color to RGB({}, {}, {})", r, g, b),
}
}
fn main() {
let msg = Message::Move { x: 10, y: 20 };
process_message(msg);
}What will this program print?
Look at how the enum variant and pattern matching work together.
The variable msg is the Move variant with x=10 and y=20. The match prints 'Move to (10, 20)'.