The following test case cannot be understood without explanation of how rust handles the temporary values:
|
#[test] |
|
fn it_works() { |
|
let counter = Rc::new(RefCell::new(0)); |
|
let _ = DropTracker::new((), Rc::clone(&counter)); |
|
assert_eq!(*counter.borrow(), 1); |
|
} |
The use of the wildcard _ as the binding target in the test case
it_works() signals to the compiler that the value is only temporary, leading to its immediate drop at the statement's conclusion. In contrast, assigning to a named variable in the test case
multiple() ensures the variable's full lifetime within its defining scope:
|
#[test] |
|
fn multiple() { |
|
let counter = Rc::new(RefCell::new(0)); |
|
|
|
{ |
|
let a = DropTracker::new(5, Rc::clone(&counter)); |
|
let b = DropTracker::new(6, Rc::clone(&counter)); |
|
} |
|
|
|
assert_eq!(*counter.borrow(), 2); |
|
} |
To suppress the compiler warning, unused vars
a and
b should be prefixed by
_.
The following test case cannot be understood without explanation of how rust handles the temporary values:
100-exercises-to-learn-rust/exercises/07_threads/06_interior_mutability/src/lib.rs
Lines 28 to 33 in d347d1f
The use of the wildcard _ as the binding target in the test case
it_works()signals to the compiler that the value is only temporary, leading to its immediate drop at the statement's conclusion. In contrast, assigning to a named variable in the test casemultiple()ensures the variable's full lifetime within its defining scope:100-exercises-to-learn-rust/exercises/07_threads/06_interior_mutability/src/lib.rs
Lines 35 to 45 in d347d1f
To suppress the compiler warning, unused vars
aandbshould be prefixed by_.