News for hackers. Stuff that matters.
Re:Indirect ownership, shallow borrow and self-referential d... by uncomputation on Saturday April 30, 2022 @11:33AM (#31216784)
The “invisible stack frame” idea is genius and so elegant. I’m currently working on a file parser in Rust and have run into this issue several times now, especially when I really want to avoid heap allocation (say the references to the file contents are MB in size).
Re:Indirect ownership, shallow borrow and self-referential d... by simulate-me on Saturday April 30, 2022 @10:22PM (#31221541)
Wouldn’t anything of variable size require a heap allocation?
Re:Indirect ownership, shallow borrow and self-referential d... by db48x on Sunday May 01, 2022 @09:04AM (#31224703)
Right, but a Vec is basically a tuple containing a pointer to allocated memory on the heap, the capacity of the allocation, and the length of the Vec. That tuple is what lives in the stack, or in a struct in the example from the article. The tuple has a fixed size, known at compile time, so it is perfectly fine for it to live on the stack. In fact, it is also ok to move a Vec around in memory; the pointer will still point to the same allocation on the heap. The problems don’t start until you want to both borrow (take references to) individual elements stored in the Vec, and also move or resize the heap allocation. That’s where the borrow checker must step in.