use crate::List::{Cons,Nil}; use std::rc::Rc; use std::cell::RefCell; // enum List { // Cons(i32,BoxList),//只能单一所有者 允许编译时执行不可变或者科比借用检查 // Nil, // } // fn main() { // let list Cons(1, // Box::new(Cons(2, // Box::new(Cons(3, // Box::new(Nil)))))); // let a Cons(5,Box::new(Cons(10,Box::new(Nil)))); // let b Cons(3,Box::new(a)); // let c Cons(4,Box::new(a));//报错 // } // enum List { //通过Rc 形成了只读的共享 // Cons(i32,RcList), //可以多个所有者 仅仅允许在编译时执行不可变检查 // Nil, // } #[derive(Debug)] enum List { Cons(RcRefCelli32,RcList), //允许运行状态下 Nil, } fn main() { /* let a Rc::new(Cons(5,Rc::new(Cons(10,Rc::new(Nil))))); println!(a ---{},Rc::strong_count(a)); { let b Cons(3,Rc::clone(a)); let b Cons(3,a.clone()); //这样也可以 println!(b ---{},Rc::strong_count(a)); } let c Cons(4,Rc::clone(a)); let c Cons(4,a.clone()); //这样也可以 println!(c ---{},Rc::strong_count(a)); */ let value Rc::new(RefCell::new(5)); let x Rc::new(Cons(Rc::clone(value),Rc::new(Nil))); let y Cons(Rc::new(RefCell::new(6)),Rc::clone(x)); let z Cons(Rc::new(RefCell::new(7)),x.clone()); println!(x before: {:?},x); println!(y before: {:?},y); println!(z before: {:?},z); println!(); *value.borrow_mut() 10; println!(x after: {:?},x); println!(y after: {:?},y); println!(z after: {:?},z); }
rust 学习 智能指针
use crate::List::{Cons,Nil}; use std::rc::Rc; use std::cell::RefCell; // enum List { // Cons(i32,BoxList),//只能单一所有者 允许编译时执行不可变或者科比借用检查 // Nil, // } // fn main() { // let list Cons(1, // Box::new(Cons(2, // Box::new(Cons(3, // Box::new(Nil)))))); // let a Cons(5,Box::new(Cons(10,Box::new(Nil)))); // let b Cons(3,Box::new(a)); // let c Cons(4,Box::new(a));//报错 // } // enum List { //通过Rc 形成了只读的共享 // Cons(i32,RcList), //可以多个所有者 仅仅允许在编译时执行不可变检查 // Nil, // } #[derive(Debug)] enum List { Cons(RcRefCelli32,RcList), //允许运行状态下 Nil, } fn main() { /* let a Rc::new(Cons(5,Rc::new(Cons(10,Rc::new(Nil))))); println!(a ---{},Rc::strong_count(a)); { let b Cons(3,Rc::clone(a)); let b Cons(3,a.clone()); //这样也可以 println!(b ---{},Rc::strong_count(a)); } let c Cons(4,Rc::clone(a)); let c Cons(4,a.clone()); //这样也可以 println!(c ---{},Rc::strong_count(a)); */ let value Rc::new(RefCell::new(5)); let x Rc::new(Cons(Rc::clone(value),Rc::new(Nil))); let y Cons(Rc::new(RefCell::new(6)),Rc::clone(x)); let z Cons(Rc::new(RefCell::new(7)),x.clone()); println!(x before: {:?},x); println!(y before: {:?},y); println!(z before: {:?},z); println!(); *value.borrow_mut() 10; println!(x after: {:?},x); println!(y after: {:?},y); println!(z after: {:?},z); }