Skip to content

Instantly share code, notes, and snippets.

@rust-play
Created July 12, 2018 15:53
Show Gist options
  • Save rust-play/e506a676c0950a146553333d26e87a3d to your computer and use it in GitHub Desktop.
Save rust-play/e506a676c0950a146553333d26e87a3d to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
use std::rc::Rc;
use std::cell::RefCell;
use List::{Cons, Nil};
#[derive(Debug)]
enum List {
Cons(i32, RefCell<Rc<List>>),
Nil,
}
impl List {
fn tail(&self) -> Option<&RefCell<Rc<List>>> {
match *self {
Cons(_, ref item) => Some(item),
Nil => None,
}
}
}
fn main() {
let a = Rc::new(Cons(5, RefCell::new(Rc::new(Nil))));
println!("a initial rc count = {}", Rc::strong_count(&a));
println!("a next item = {:#?}", a.tail());
let b = Rc::new(Cons(10, RefCell::new(Rc::clone(&a))));
println!("a initial rc count after b creation = {}", Rc::strong_count(&a));
println!("b initial rc count = {}", Rc::strong_count(&b));
println!("b next item = {:#?}", b.tail());
if let Some(link) = a.tail() {
*link.borrow_mut() = Rc::clone(&b);
}
println!("b rc count after changing a = {}", Rc::strong_count(&b));
println!("a rc count after changing a = {}", Rc::strong_count(&a));
//println!("a next item = {:#?}", a.tail());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment