Rust Essentials
48 cards · 🇺🇸 English
Ownership, borrowing, and core Rust syntax.
Study all 48 cards for free
Flashcards, quizzes, pixel-art games and a daily review that remembers for you.
Try the first 10 cards
1 / 10Rust
Tap the card for the answer · swipe right if you knew it, left if not
Already have an account? Sign in
Cards
- 1RustSystems programming language focused on safety, speed, and concurrency. Memory-safe without garbage collection through ownership system. Created by Mozilla, first released 2015
- 2Write a basic Hello World in Rustfn main() { println!("Hello, World!"); } Run: rustc main.rs && ./main Or with Cargo: cargo run
- 3Ownership in RustCore memory management concept. Each value has a single owner variable. When owner goes out of scope, value is dropped (memory freed). Prevents double-free, dangling pointers
- 4Three ownership rules1. Each value has exactly one owner 2. When owner goes out of scope, value is dropped 3. There can only be one owner at a time (moves transfer ownership)
- 5Borrowing in RustCreating references to values without taking ownership: let s = String::from("hello"); let r = &s; // immutable borrow let r = &mut s; // mutable borrow Original owner still valid after borrow ends
- 6Borrowing rules1. Any number of immutable references (&T) OR 2. Exactly one mutable reference (&mut T) Never both at same time. Prevents data races at compile time
- 7String vs &strString: owned, heap-allocated, mutable, growable let s = String::from("hello"); &str: string slice, borrowed, immutable, fixed size let s: &str = "hello"; // string literal
- 8How do variables work in Rust?let x = 5; // immutable by default let mut y = 10; // mutable y = 20; // OK x = 10; // ERROR! const MAX: i32 = 100; // constant, must have type
- 9Rust's basic typesIntegers: i8/16/32/64/128, u8/16/32/64/128, isize/usize Floats: f32, f64 Boolean: bool Character: char (4 bytes, Unicode) Tuple: (i32, f64, bool) Array: [i32; 5]
- 10Pattern matching in Rustmatch value { 1 => println!("one"), 2 | 3 => println!("two or three"), 4..=10 => println!("four to ten"), _ => println!("something else"), } Must be exhaustive (cover all cases)
- 11Option<T>enum Option<T> { Some(T), None, } Rust's null replacement. Forces explicit handling: match opt { Some(val) => println!("{}", val), None => println!("no value"), }
- 12Result<T, E>enum Result<T, E> { Ok(T), Err(E), } For operations that can fail: fn divide(a: f64, b: f64) -> Result<f64, String> { if b == 0.0 { Err("division by zero".to_string()) } else { Ok(a / b) } }
- 13? operatorPropagates errors - returns early if Err: fn read_file() -> Result<String, Error> { let mut file = File::open("file.txt")?; // returns if Err let mut contents = String::new(); file.read_to_string(&mut contents)?; Ok(contents) } Syntactic sugar for error handling
- 14Struct in Ruststruct User { username: String, email: String, active: bool, } let user = User { username: String::from("john"), email: String::from("john@example.com"), active: true, };
- 15Define methods on structsimpl User { fn new(username: String, email: String) -> Self { User { username, email, active: true, } } fn greet(&self) { println!("Hello, {}!", self.username); } }
- 16Enum in Rustenum Message { Quit, Move { x: i32, y: i32 }, Write(String), ChangeColor(i32, i32, i32), } let msg = Message::Write(String::from("hello")); match msg { Message::Write(text) => println!("{}", text), // ... }
- 17Trait in RustDefines shared behavior (like interfaces): trait Summary { fn summarize(&self) -> String; } impl Summary for Article { fn summarize(&self) -> String { format!("{}: {}", self.headline, self.author) } }
- 18Common standard traitsClone: .clone() for deep copy Copy: bitwise copy (integers, etc.) Debug: {:?} formatting Display: {} formatting Drop: cleanup on drop Eq/PartialEq: equality Ord/PartialOrd: ordering Iterator: iteration
- 19Lifetime in RustAnnotation telling compiler how long references are valid: fn longest<'a>(x: &'a str, y: &'a str) -> &'a str { if x.len() > y.len() { x } else { y } } Prevents dangling references. Often inferred automatically
- 20Vec vs arrayVec<T>: dynamic size, heap-allocated let v = vec![1, 2, 3]; v.push(4); [T; N]: fixed size, stack-allocated let a: [i32; 5] = [1, 2, 3, 4, 5]; Vec is more common
- 21Iterate in Rustfor i in 0..5 { } // 0 to 4 for i in 0..=5 { } // 0 to 5 inclusive for item in &vec { } // immutable for item in &mut vec { } // mutable for item in vec { } // takes ownership while condition { } loop { } // infinite
- 22Unwrap() and when should you use itExtracts value from Option/Result, panics if None/Err: let x = Some(5).unwrap(); // 5 let x = None.unwrap(); // PANIC! Use only when certain it won't panic, or use expect() with message: let x = file.expect("Failed to open file");
- 23Closures in RustAnonymous functions that can capture environment: let add = |x, y| x + y; let result = add(5, 3); let x = 5; let closure = |y| x + y; // captures x Types inferred from usage
- 24Three closure traitsFn: borrows immutably FnMut: borrows mutably FnOnce: takes ownership (can only call once) fn apply<F: Fn(i32) -> i32>(f: F, x: i32) -> i32 { f(x) }
- 25.iter(), .iter_mut(), vs .into_iter().iter(): immutable references (&T) for item in vec.iter() { } .iter_mut(): mutable references (&mut T) for item in vec.iter_mut() { *item += 1; } .into_iter(): takes ownership (T) for item in vec.into_iter() { } // vec no longer usable
- 26Box, Rc, and ArcBox<T>: heap allocation, single owner let b = Box::new(5); Rc<T>: reference counting, multiple owners (not thread-safe) let rc = Rc::new(5); Arc<T>: atomic ref counting, thread-safe multiple ownership let arc = Arc::new(5);
- 27RefCell<T>Interior mutability - allows mutable borrows of immutable data: let cell = RefCell::new(5); *cell.borrow_mut() += 1; Borrowing rules checked at RUNTIME (panics if violated) Use when you know borrowing is safe but compiler can't prove it
- 28Mutex<T>Mutual exclusion for thread-safe shared data: use std::sync::Mutex; let m = Mutex::new(5); { let mut num = m.lock().unwrap(); *num = 6; } // lock released Combine with Arc for shared ownership
- 29Spawn threads in Rustuse std::thread; let handle = thread::spawn(|| { println!("Hello from thread!"); }); handle.join().unwrap(); // wait for thread Use Arc<Mutex<T>> for shared data
- 30Move keyword in closuresForces closure to take ownership of captured variables: let v = vec![1, 2, 3]; let handle = thread::spawn(move || { println!("{:?}", v); }); // v no longer accessible here Necessary for thread safety
And 18 more cards. Study the whole deck free
Articles about this deck
More Programming decks
See all- 🐹
Go Essentials
49 cards · 🇺🇸 English
Core Go syntax: goroutines, channels, slices, and error handling.
- 🐦
Swift Essentials
48 cards · 🇺🇸 English
Core Swift syntax, optionals, and iOS-friendly language features.
- 🎯
Kotlin Essentials
42 cards · 🇺🇸 English
Core Kotlin syntax, null safety, and Android-friendly language features.
- 🧱
Data Structures
95 cards · 🇺🇸 English
Arrays, linked lists, trees, graphs, hash tables and their core operations.
- 🟣
C#: Fundamentals & .NET Core
99 cards · 🇺🇸 English
Core C# syntax, types, and .NET Core concepts in one deck.
- 🌐
APIs: REST, GraphQL & HTTP Status Codes
108 cards · 🇺🇸 English
REST and GraphQL API concepts plus common HTTP status codes.
