Skip to content

Instantly share code, notes, and snippets.

@octave99
Created June 27, 2019 13:37
Show Gist options
  • Save octave99/88e454fc0e4ee6f63d64a5f81ec14e6d to your computer and use it in GitHub Desktop.
Save octave99/88e454fc0e4ee6f63d64a5f81ec14e6d to your computer and use it in GitHub Desktop.
pub struct MyStruct<'a> {
name: &'a str,
}
impl<'a> MyStruct<'a> {
fn new() -> Self {
MyStruct { name: "Before" }
}
fn read(&self) {
print!("Value is {}\n", self.name);
}
fn write(&mut self) {
self.name = "After";
print!("Value is now {}\n", self.name);
}
}
fn error_fn() {
let mut ms = MyStruct::new();
let reader = &ms;
reader.read();
// let mut _writer = &mut ms; // Error: cannot borrow `ms` as mutable because it is also borrowed as immutable
}
fn good_fn() {
let mut ms = MyStruct::new();
{
let reader = &ms;
reader.read();
}
{
let mut _writer = &mut ms;
_writer.write();
}
{
let reader = &ms;
reader.read();
}
}
fn cell_fn() {
let c = std::cell::RefCell::new(MyStruct::new());
c.borrow().read();
c.borrow_mut().write();
c.borrow().read();
c.borrow_mut().write();
}
fn main() {
error_fn();
cell_fn();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment