fn main()
rust.quest
Fearless concurrency. Memory safety. Zero-cost abstractions. Begin your quest into systems programming.
compiled successfully
Chapter 1
Ownership
Each value in Rust has a single owner. When the owner goes out of scope, the value is dropped. This is Rust's fundamental contract.
"hello"
"hello"
ownership.rs
let s1 = String::from("hello");
let s2 = s1; // s1 is moved
// println!("{}", s1); // ERROR: value used after move
println!("{}", s2); // OK
Chapter 2
Borrowing
References allow you to refer to a value without taking ownership. Immutable references (&T) share freely; mutable references (&mut T) are exclusive.
data
data
borrowing.rs
fn calculate_length(s: &String) -> usize {
s.len()
} // s goes out of scope, but doesn't drop the value
let s1 = String::from("hello");
let len = calculate_length(&s1);
println!("len of '{}' is {}", s1, len);
Chapter 3
Lifetimes
Lifetimes ensure references are valid for as long as they're used. The borrow checker verifies this at compile time.
lifetimes.rs
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() { x } else { y }
}
Quest Complete
Compilation Successful
Compiling rust-quest v1.0.0
Finished release [optimized]
Running `target/release/rust-quest`
Quest complete. You are now a Rustacean.
_~^~^~_ \) / o o \ (/ '_ - _' / '-----' \