Rust Advance Cheatsheet

Syed Muhammad Ali Raza - May 12 - - Dev Community

Introduction

Rust is a multi-paradigm programming language designed for
Performance and safety, especially safe concurrency.
Rust is syntactically similar to C++, but can guarantee memory safety by using a borrow checker to validate references. The Advance Cheatsheet of Rust is

1. Ownership and Borrowing:

fn main() {
    let s1 = String::from("hello ali");
    let s2 = s1; 
    println!("{}", s2);
    println!("{}", s1); 
}
Enter fullscreen mode Exit fullscreen mode

2. Error Handling:

use std::fs::File;
use std::io::{self, Read};

fn read_username_from_file() -> Result<String, io::Error> {
    let mut f = File::open("username.txt")?;
    let mut s = String::new();
    f.read_to_string(&mut s)?;
    Ok(s)
}
Enter fullscreen mode Exit fullscreen mode

3. Concurrency:

use std::thread;
use std::sync::mpsc;

fn main() {
    let (tx, rx) = mpsc::channel();
    let handle = thread::spawn(move || {
        let val = String::from("hello");
        tx.send(val).unwrap();
    });
    let received = rx.recv().unwrap();
    println!("Got: {}", received);
    handle.join().unwrap();
}
Enter fullscreen mode Exit fullscreen mode

4. Traits and Generics:

trait Animal {
    fn name(&self) -> &'static str;
}

struct Dog;

impl Animal for Dog {
    fn name(&self) -> &'static str {
        "Dog"
    }
}

fn print_name<T: Animal>(animal: T) {
    println!("This is a {}", animal.name());
}
Enter fullscreen mode Exit fullscreen mode

5. Pattern Matching:

fn main() {
    let number = Some(7);
    match number {
        Some(7) => println!("Lucky number 7!"),
        Some(n) => println!("Some other number: {}", n),
        None => (),
    }
}
Enter fullscreen mode Exit fullscreen mode

6. Advanced Data Structures:

use std::collections::HashMap;
[](url)
fn main() {
    let mut scores = HashMap::new();
    scores.insert(String::from("Blue"), 10);
    scores.insert(String::from("Yellow"), 50);
    for (key, value) in &scores {
        println!("{}: {}", key, value);
    }
}
Enter fullscreen mode Exit fullscreen mode

7. Unsafe Rust:

unsafe fn dangerous() {
    println!("This is unsafe!");
}

fn main() {
    unsafe {
        dangerous();
    }
}
Enter fullscreen mode Exit fullscreen mode

Follow for more content
Here is my Linkedin Profile Syed Muhammad Ali Raza

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .