6ft Dan
6ft Dan

Reputation: 2445

What happens to the no-longer-referenced chunk when I reassign half of a linked list?

I have successfully implemented a custom numeric base system in Rust via linked lists called digits.

pub struct Digits<'a> {
    mapping: &'a BaseCustom<char>,
    digit: u64,
    left: Option<Box<Digits<'a>>>,
}

I've declared a lifetime on the linked list struct and linked it directly to an instance of BaseCustom. When I reassign half of the linked list, what happens to the unreferenced chunk which still has its lifetime associated with the BaseCustom mapping?

For example, I have a linked list that looks like "hello" (I'll use left to right for this example and not right to left as in my project)

h -> e -> l -> l -> o

Then I reassign the linked list reference from e to a different set of characters.

h -> e    l -> l -> o
      \
       -> d -> g-> e

Now that the code is no longer using the "llo" of hello, does that memory automatically get freed? Does the fact that each character instance here have a reference to BaseCustom's lifetime mean that the memory is held on to until the program ends?

I know Rust doesn't have or use a garbage collector so the lifetime reference to BaseCustom confuses me here. Is it stating that the items must live as long as BaseCustom? Or is it that they get freed up at some point but BaseCustom must outlive them?

Upvotes: 0

Views: 99

Answers (1)

Shepmaster
Shepmaster

Reputation: 431489

Does the fact that each character instance here have a reference to BaseCustom's lifetime mean that the memory is held on to until the program ends?

Say it with me:

Lifetime annotations don’t change how long any of the references involved live

Or the jargon version you might see elsewhere:

Lifetimes are descriptive, not prescriptive.

The fact that there are lifetimes present does not change the behavior of your code.

When you overwrite left with a new value, nothing knows about the old value so it must be dropped. In this case, that means a value of type Option<Box<Digits<'a>>> is dropped. If it's a Some, this calls the destructor for Box which would in turn call the destructor for Digits, which will call the destructor for mapping, digit, and recursively for its own left.

What does dropping a reference or an integer do? Absolutely nothing.

Is it stating that the items must live as long as BaseCustom? Or is it that they get freed up at some point but BaseCustom must outlive them?

The lifetime states that Digits may not outlive BaseCustom. This makes sense because it contains a reference to BaseCustom.


See also:

Upvotes: 1

Related Questions