Skip to content

Instantly share code, notes, and snippets.

@BSN4
Last active January 8, 2025 18:09
Show Gist options
  • Save BSN4/e7f92ee41aa064f413eb1856e29c251f to your computer and use it in GitHub Desktop.
Save BSN4/e7f92ee41aa064f413eb1856e29c251f to your computer and use it in GitHub Desktop.
rust non-async ownership

Rust Borrowing and Ownership Rules

Struct Methods

Use &mut self when:

  • Modifying struct fields (e.g., update_score, play_round)
  • Maintaining state between calls

Use &self when:

  • Only reading values (e.g., get_player_move, announce_winner)
  • No state changes needed

Use self when:

  • Taking ownership (rare, usually for cleanup/destruction)

Functions

fn read_only(data: &Vec<i32>)      // Borrow to read
fn modify(data: &mut Vec<i32>)      // Borrow to modify
fn take_ownership(data: Vec<i32>)   // Transfer ownership

Variables

let x = 5;              // Owned value
let y = &x;             // Immutable borrow 
let mut z = 5;          // Mutable owned value
let w = &mut z;         // Mutable borrow

Core Rules

  • One mutable reference OR many immutable references (not both)
  • References must not outlive the data they refer to
  • Data can only have one owner at a time

Traits

Implementation Rules

  • Use &self for trait methods that only read data
  • Use &mut self when the trait method needs to modify the implementing type
  • Trait bounds can specify if a reference is mutable: T: MyTrait vs &mut T: MyTrait

Common Examples

trait Read {
    fn read(&self) -> String;  // Only needs reading access
}

trait Write {
    fn write(&mut self, data: &str);  // Needs modification access
}

trait Drop {
    fn drop(self);  // Takes ownership for cleanup
}

Enums

Best Practices

#[derive(Debug, PartialEq, Clone, Copy)]
enum GameState {
    Playing,
    Won,
    Lost,
}
  • Always derive these traits to avoid ownership issues:
    • Debug: For printing and debugging
    • PartialEq: For comparisons
    • Clone, Copy: For easy value copying
  • Exception: Skip Copy for enums containing non-Copy types (e.g., String, Vec)

Common Patterns

// Temporary borrow
let mut v = vec![1,2,3];
v.iter_mut().for_each(|x| *x += 1);

// Transfer ownership
let s = String::from("hello");
takes_ownership(s); // s is invalid after this
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment