Trying to find a way not to return a temporary after an RefCell borrow

⚓ Rust    📅 2026-05-20    👤 surdeus    👁️ 2      

surdeus

Here's an approach to back references which mostly works, but I'm not quite there yet.

The concept is single ownership using Rc<RefCell> with restrictions. That's encapsulated in a type Owner. You can't clone Owner, but you can get a weak pointer from the Rc. Then you can upgrade and borrow to use the value.

The new thing here is that, when an Owner is dropped, there's a check that there are no remaining weak or strong references. Those are not allowed to outlive the Owner. Thus, upgrade cannot fail. Of course, borrow can still fail. The idea is to use small non-overlapping borrow scopes so that borrow clashes are eliminated.

This creates an ergonomics problem and an overhead problem. First step is to fix the ergonomics. Currently, I have to write

w_weak.cell.upgrade().unwrap().borrow_mut().x = 100.0;
let xval1 = w_weak.cell.upgrade().unwrap().borrow().x;

I'd like to be able to write

w_weak.borrow_mut().x = 100.0;
let xval2 = w_weak.borrow().x;

which is less of a pain.

But the implementation of WeakOwner, which is currently commented out, returns a temporary. Remove the "/*" comment markers and try to compile. I don't have a workaround for that. That's what I'm looking for.

(Ignore performance issues. That comes later.)
(Similar problem from 2018: Need help getting borrow checker to pass with Rc<RefCell<_>>)

6 posts - 5 participants

Read full topic

🏷️ Rust_feed