Skip to content

Instantly share code, notes, and snippets.

@anoopelias
Last active March 11, 2024 12:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anoopelias/75cd7163af9a007755086745a742118a to your computer and use it in GitHub Desktop.
Save anoopelias/75cd7163af9a007755086745a742118a to your computer and use it in GitHub Desktop.
Rust101_Session3

Rust 101 - Session 3

Recap

Ownership

fn main() {
    let nums = vec![2, 4, 6];
    let nums2 = nums;

    println!("{:?}", nums2);
}

Immutable Borrow

fn main() {
    let nums = vec![2, 4, 6];
    print_nums(nums);

    println!("{:?}", nums);
}

fn print_nums(nums: Vec<i32>) {
    for num in nums.iter() {
        println!("{}", num)
    }
}

Multiple immutable borrow

fn main() {
    let nums = vec![2, 4, 6];
    let nums2 = &nums;
    let nums3 = &nums;
    let nums4 = &nums;

    println!("{:?} {:?} {:?}", nums2, nums3, nums4);
}

Mutable borrow

fn main() {
    let nums = vec![2, 4, 6];
    extend_nums(nums);

    println!("{:?}", nums);
}

fn extend_nums(mut nums: Vec<i32>) {
    nums.push(8);
}

Structs

  • Classic struct - Color
  • Create object and access values
  • Debug print
  • Mutability of values
  • Update for Tuple Struct
  • Unit Struct
  • Struct of a package with strings and weight
  • Impl of ownership
  • Impl of reference
  • How to call a reference?
  • Impl of add weight
  • How to call a mut reference?

Enums

  • Example of Message - Echo, Move, ChangeColor, Quit
  • If else enum and PartialEq
impl PartialEq for Message {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (Message::Quit, Message::Quit) => true,
            (Message::Echo, Message::Echo) => true,
            (Message::Move, Message::Move) => true,
            (Message::ChangeColor, Message::ChangeColor) => true,
            _ => false,
        }
    }
}

  • Enum with values
  • Print - Debug
  • Impl for call
  • Match

String

  • String::from for foobar
  • How to get a slice from a string
  • Trim string
  • Replace bar with baz
  • Replacement needs a new String. Why?
  • String concatenation
    • push_str
    • format!

Modules

  • Crate root
  • mod foo and how to call
  • mod bar and how to call foo from there
  • export and import
  • Separate into files
  • Separate into folders
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment