MCPcopy Create free account
hub / github.com/QMHTMY/RustBook / main

Function main

publication/code/chapter01/use_weak.rs:16–40  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

14}
15
16fn main() {
17 let car: Rc<Car> = Rc::new(
18 Car {
19 name: "Tesla".to_string(),
20 wheels: RefCell::new(vec![]),
21 }
22 );
23 let wl1 = Rc::new(Wheel { id:1, car: Rc::downgrade(&car) });
24 let wl2 = Rc::new(Wheel { id:2, car: Rc::downgrade(&car) });
25
26 {
27 let mut wheels = car.wheels.borrow_mut();
28 // downgrade 得到 Weak
29 wheels.push(Rc::downgrade(&wl1));
30 wheels.push(Rc::downgrade(&wl2));
31 } // 确保借用结束
32
33 for wheel_weak in car.wheels.borrow().iter() {
34 if let Some(wl) = wheel_weak.upgrade() {
35 println!("wheel {} owned by {}", wl.id, wl.car.upgrade().unwrap().name);
36 } else {
37 println!("wheel weak reference has been dropped");
38 }
39 }
40}

Callers

nothing calls this directly

Calls 3

to_stringMethod · 0.45
pushMethod · 0.45
iterMethod · 0.45

Tested by

no test coverage detected