🦀

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.

Study this deck free

Try the first 10 cards

1 / 10
Question

Rust

Knew itLearning

Tap the card for the answer · swipe right if you knew it, left if not

Already have an account? Sign in

Cards

  1. 1Rust
    Systems programming language focused on safety, speed, and concurrency. Memory-safe without garbage collection through ownership system. Created by Mozilla, first released 2015
  2. 2Write a basic Hello World in Rust
    fn main() { println!("Hello, World!"); } Run: rustc main.rs && ./main Or with Cargo: cargo run
  3. 3Ownership in Rust
    Core 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
  4. 4Three ownership rules
    1. 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)
  5. 5Borrowing in Rust
    Creating 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
  6. 6Borrowing rules
    1. 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
  7. 7String vs &str
    String: owned, heap-allocated, mutable, growable let s = String::from("hello"); &str: string slice, borrowed, immutable, fixed size let s: &str = "hello"; // string literal
  8. 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
  9. 9Rust's basic types
    Integers: 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]
  10. 10Pattern matching in Rust
    match 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)
  11. 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"), }
  12. 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. 13? operator
    Propagates 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
  14. 14Struct in Rust
    struct User { username: String, email: String, active: bool, } let user = User { username: String::from("john"), email: String::from("john@example.com"), active: true, };
  15. 15Define methods on structs
    impl User { fn new(username: String, email: String) -> Self { User { username, email, active: true, } } fn greet(&self) { println!("Hello, {}!", self.username); } }
  16. 16Enum in Rust
    enum 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), // ... }
  17. 17Trait in Rust
    Defines shared behavior (like interfaces): trait Summary { fn summarize(&self) -> String; } impl Summary for Article { fn summarize(&self) -> String { format!("{}: {}", self.headline, self.author) } }
  18. 18Common standard traits
    Clone: .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
  19. 19Lifetime in Rust
    Annotation 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
  20. 20Vec vs array
    Vec<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
  21. 21Iterate in Rust
    for 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
  22. 22Unwrap() and when should you use it
    Extracts 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");
  23. 23Closures in Rust
    Anonymous 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
  24. 24Three closure traits
    Fn: 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. 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
  26. 26Box, Rc, and Arc
    Box<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);
  27. 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
  28. 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
  29. 29Spawn threads in Rust
    use std::thread; let handle = thread::spawn(|| { println!("Hello from thread!"); }); handle.join().unwrap(); // wait for thread Use Arc<Mutex<T>> for shared data
  30. 30Move keyword in closures
    Forces 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
Study all 48 cards free