Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use std::ops::{Deref, DerefMut};
- use std::rc::{Rc, Weak};
- use std::cell::RefCell;
- use crate::List::{Cons, Nil};
- #[derive(Clone,Debug)]
- enum List<Link> {
- Cons(i32, RefCell<Link>),
- Nil,
- }
- impl<Link> List<Link> {
- fn tail(&self) -> Option<&RefCell<Link>> {
- match self {
- Cons(_, item) => Some(item),
- Nil => None,
- }
- }
- }
- #[derive(Clone,Debug)]
- struct RcLink(pub Rc<List<RcLink>>);
- impl Deref for RcLink {
- type Target = Rc<List<RcLink>>;
- fn deref(&self) -> &Self::Target { &self.0 }
- }
- impl DerefMut for RcLink {
- fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 }
- }
- #[derive(Clone,Debug)]
- struct WeakLink(pub Weak<List<WeakLink>>);
- impl Deref for WeakLink {
- type Target = Weak<List<WeakLink>>;
- fn deref(&self) -> &Self::Target { &self.0 }
- }
- impl DerefMut for WeakLink {
- fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 }
- }
- fn main() {
- let a = RcLink(Rc::new(Cons(5, RefCell::new(RcLink(Rc::new(Nil))))));
- println!("a initial rc count = {}", Rc::strong_count(&a));
- println!("a next item = {:?}", a.tail());
- let b = RcLink(Rc::new(Cons(10, RefCell::new(a.clone()))));
- println!("a 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() = b.clone();
- }
- println!("b rc count after changing a = {}", Rc::strong_count(&b));
- println!("a rc count after changing a = {}", Rc::strong_count(&a));
- // Uncomment the next line to see that we have a cycle;
- // it will overflow the stack
- // println!("a next item = {:?}", a.tail());
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement