rustbook_learning_guide/
smart_pointers.rs1use std::rc::Rc;
4use std::cell::RefCell;
5
6pub fn smart_pointer_examples() {
7 println!("\n🧠Smart Pointer Examples");
8 println!("{}", "-".repeat(27));
9
10 let boxed = Box::new(5);
12 println!("Boxed value: {}", boxed);
13
14 let rc = Rc::new(10);
16 let rc_clone = Rc::clone(&rc);
17 println!("Rc value: {}, clone: {}", rc, rc_clone);
18
19 let ref_cell = RefCell::new(20);
21 *ref_cell.borrow_mut() += 5;
22 println!("RefCell value: {}", ref_cell.borrow());
23}
24
25#[derive(Debug)]
26pub struct Shoe {
27 size: u32,
28 style: String,
29}
30
31impl Shoe {
32 pub fn new(size: u32, style: &str) -> Self {
33 Shoe {
34 size,
35 style: style.to_string(),
36 }
37 }
38}
39
40pub fn shoes_in_size(shoes: Vec<Shoe>, shoe_size: u32) -> Vec<Shoe> {
41 shoes.into_iter().filter(|s| s.size == shoe_size).collect()
42}
43
44#[derive(Debug)]
45pub enum List {
46 Cons(i32, Box<List>),
47 Nil,
48}
49
50impl List {
51 pub fn new(values: Vec<i32>) -> Box<List> {
52 let mut result = Box::new(List::Nil);
53 for value in values.into_iter().rev() {
54 result = Box::new(List::Cons(value, result));
55 }
56 result
57 }
58}
59
60
61