Hacker News new | past | comments | ask | show | jobs | submit login

Regarding traits: you can have Rc<Trait> (by casting from Rc<your concrete type>), but not RefCell<Trait>. The reason is that Rc is a pointer, so the size of Rc<Trait> can be constant regardless of the size of the type implementing the trait. But if you actually want a weak reference inside a refcell (as opposed to the other way around), RefCell<Weak<Trait>> should work fine. Also consider the Cell type, which has a more limited API than RefCell but zero overhead.

Regarding everything being destructed at once: that’s called an arena, and there are crates for it:

https://crates.io/crates/typed-arena




> Regarding everything being destructed at once: that’s called an arena

Thats such a great name :)


It is quite common name for memory pools.


Arenas have more to do with the allocation pattern, they don't solve the cycle problem, right?


You're correct, that crate doesn't solve the cycle problem. There is a different way of doing arenas in Rust that does though.

What you do is you put all of your tree nodes in a big Vec<Node> and instead of referring to children and parents via pointers, you do so via indices. It's less convenient because you have to pass around a reference to your "arena" everywhere (the Vec or a slice of it), and it incurs bounds checks (pretty cheap though). But, it solves the problem in a way that is guaranteed safe.


In a sense, they solve the cycle problem in Rust. The trick is that once something is allocated to an arena, it has the same lifetime as the whole arena, and that allows cyclical links because none of the nodes "outlive each other".

However, you must have interior mutability (achieved using Cell types), because otherwise you can't mutate the parent nodes to add links to child nodes.

Check the typed arena crate in crates.io and the Cell type in the standard library.




Consider applying for YC's Spring batch! Applications are open till Feb 11.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: