Learning Rust: How to access Weak<List> implementation of cons list in a loop? (from rust book)

Hi, I am learning rust and reading the rust book at this section Reference Cycles Can Leak Memory - The Rust Programming Language.

It talks about people can use Weak Instead of Rc to avoid Reference Cycle problem. But it doesn't provide a Weak implementation. Thus I tried to do it by myself.

Since I am a newbie, I might be completely wrong. Here is my implementation: Rust Playground

Since it's a infinite cycle, I tried to print 5 tails in a loop.
If I only print one tail without the for loop, it works fine.
But inside the loop, the compiler will complain borrowed value does not live long enough. It seems the borrowed value can not be used inside a loop.

I tried to fix the problem for a whole day and tried many things including using global variables. But none of the trials works.

Can anyone please help me on this?

Thank you very much.

This doesn't mean replace Rc with Weak. It means that only replace one of them to avoid a cycle.

Thanks a lot for the reply. Since I am a newbie and not a native English speaker too, I don't really get what you mean and what to do.

Btw, do you know how to make the loop work based on my current implementation? I am really curious how to make it work because I have spent an entire day and can not make it work.

Don't worry, so am I.

If you want to learn how to write a linked-list properly (which itself is a fairly difficult thing to do in Rust, given its type system), you can read this book. It will clear up all your doubts and teach you a bunch of new things as well.

It won't help to fix that loop, since it seems to me that you haven't yet understood how Rc and Weak work. But I think the book will clear that up.

Thank you very much for introducing the book. I will read it after completing the first rust book and async book.

Btw, I really want to make that loop work because I have spent an entire day to fight with that loop...

From what I understand, the problem is list.tail()'s list dropped in the first loop cycle, but _link.borrow().upgrade() will need to use that dropped value in the second loop cycle. I am not sure if what I understand is correct or not. I have no ideas how to fix it.

I would suggest you let go of it and focus on learning the right/better way of doing it. I understand it's been a frustrating day for you, but trust me, we've all been there.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.