Re:The Next Steps for Single Ownership and RAII
by btschaegg on Friday July 17, 2020 @02:53AM
(#23867878)
Since I'm still starting out with Rust, there's probably just something I'm missing here, but couldn't you easily solve that with `Cell<T>` or `RefCell<T>`?
Re:The Next Steps for Single Ownership and RAII
by ridiculous_fish on Friday July 17, 2020 @03:33AM
(#23868126)
I hope to see an expert answer to this question. In my lame attempt, Cell was too awkward and RefCell was also awkward with a side of runtime cost.
Consider visiting a tree:
A recursive implementation of `postorder_visit` is trivial but risks stack overflow. A heap-allocated stack (say, `Vec<&mut Tree>`) runs into problems with the borrow checker, which knows about the C stack, but not your stack.So an overflow-safe implementation must use unsafe, but still wants to have confidence in ordered destruction. You could make it a `Vec<*mut Tree>`, but now there are zero checks!
The idea here is, in debug mode only, replace `Box` with `Rc` that checks its refcount upon drop, and `&mut Tree` with Rc as well. Now your debug mode does not require unsafe, and your release mode is fast. You have dynamically enforced ownership in a regime inaccessible to the borrow checker.