Index
- Guessing Game
- Common Programming Concepts
- Understanding Ownership
- Using Structs
- Enums and Pattern Matching
- Managing Growing Projects with Packages, Crates, and Modules
- Defining Modules to Control Scope and Privacy
- Paths for Referring to an Item in the Module Tree
- Bringing Paths into Scope with the use Keyword
- Separating Modules into Different Files
- Common Collections
- Error Handling
- Generic Types, Traits, and Lifetimes
- Writing Automated Tests
- Object Oriented Programming
- Adding dependancies
- Option Take
- RefCell
- mem
- Data Structure
- Recipe
- Semi colon
- Calling rust from python
- Default
- Crytocurrency With rust
- Function chaining
- Question Mark Operator
- Tests with println
- lib and bin
- Append vector to hash map
- Random Number
- uuid4
- uwrap and option
- Blockchain with Rust
- Near Protocol
- Actix-web
RefCell
RefCell
https://doc.rust-lang.org/std/cell/struct.RefCell.html
A mutable memory location with dynamically checked borrow rules
pub fn borrow(&self) -> Ref<T>
Immutably borrows the wrapped value.
fn main() {
use std::cell::RefCell;
let c = RefCell::new(5);
let borrowed_five = c.borrow();
let borrowed_five2 = c.borrow();
println!("{}", borrowed_five); // 5
println!("{}", borrowed_five2); // 5
}
use std::cell::RefCell;
let c = RefCell::new(5);
let borrowed_five = c.borrow();
let borrowed_five2 = c.borrow();
println!("{}", borrowed_five); // 5
println!("{}", borrowed_five2); // 5
}
pub fn borrow_mut(&self) -> RefMut<T>
Mutably borrows the wrapped value.
use std::cell::RefCell;
let c = RefCell::new(5);
*c.borrow_mut() = 7;
assert_eq!(*c.borrow(), 7);
let c = RefCell::new(5);
*c.borrow_mut() = 7;
assert_eq!(*c.borrow(), 7);
Error code:
fn main() {
use std::cell::RefCell;
let c = RefCell::new(5);
c.borrow_mut() = 7;
}
use std::cell::RefCell;
let c = RefCell::new(5);
c.borrow_mut() = 7;
}
Another example
fn main() {
use std::cell::RefCell;
#[derive(Clone)]
struct Node {
next: String,
}
let c = RefCell::new(Node {
next: "hello".to_owned(),
});
c.borrow_mut().next = "bye".to_owned();
println!("{:?}", c.borrow().next); // "bye"
}
use std::cell::RefCell;
#[derive(Clone)]
struct Node {
next: String,
}
let c = RefCell::new(Node {
next: "hello".to_owned(),
});
c.borrow_mut().next = "bye".to_owned();
println!("{:?}", c.borrow().next); // "bye"
}