Posts tagged with 'Rust programming'
Found 2 posts tagged with 'Rust programming'.
Adblocker Detected
It looks like you're using an adblocker. Our website relies on ads to keep running. Please consider disabling your adblocker to support us and access the content.
Rust Cheatsheet
Cheatsheet August 29, 2024
rust
use std::collections::HashMap;
let mut scores = HashMap::new();
scores.insert(String::from("Blue"), 10);
scores.insert(String::from("Yellow"), 50);
Iterating Over Collections
for i in &v {
println!("{}", i);
}
for (key, value) in &scores {
println!("{}: {}", key, value);
}
11. Concurrency
Threads
Advanced Memory Management in Rust: Understanding Ownership, Borrowing, and Lifetimes
Tutorial August 27, 2024
rust
- Ownership and Functions: Passing and returning ownership to manage resource lifecycles.
- Smart Pointers: Using types like
Box
,Rc
, andRefCell
to manage ownership and borrowing with more flexibility.
- Interior Mutability: Allowing mutation through immutable references using patterns like
RefCell
.
Example: Using Rc
and RefCell
use std::cell::RefCell;
use std::rc::Rc;
#[derive(Debug)]
struct Node {
value: i32,
next: Option<Rc<RefCell<Node>>>,
}
fn main() {
let first = Rc::new(RefCell::new(Node { value: 1, next: None }));
let second = Rc::new(RefCell::new(Node { value: 2, next: None }));
first.borrow_mut().next = Some(Rc::clone(&second));
second.borrow_mut().next = Some(Rc::clone(&first)); // Creates a cycle, but managed by Rc and RefCell
println!("First node: {:?}", first);
}