Skip to content

Test cases for 07_threads/06_interior_mutability should be explained #306

@iurii-kyrylenko

Description

@iurii-kyrylenko

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 _.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions