3 ms·
The solution linked to in "Go has a suitable answer" isn't relevant, because it doesn't support virtual methods. You can do the same thing described there in Ru
by pcwalton 10y ago
The solution linked to in "Go has a suitable answer" isn't relevant, because it doesn't support virtual methods. You can do the same thing described there in Rust by having a base struct, embedding the base struct in any child structs (composition over inheritance), and implementing Deref/DerefMut on the child if you like.
Go has the exact same set of features Rust has here, no more: struct composition or interfaces/traits.
Regarding graphs: The best solution is option 3, using a crate on crates.io (petgraph is the most popular, but rust-forest is fine too). The preferred solution to having multiple types of nodes in the same tree is to use an enum or a trait. (Servo uses a trait for its flow tree, with downcast methods like as_block() if needed.)
I'm puzzled by the contention that the fact that all nodes have to be the same type is a problem with Rust. That's always true in any language. Even in C, you'd have to have your next/previous pointers have some type, or else you couldn't traverse the list!
- mercurial 10y ago> The preferred solution to having multiple types of nodes in the same tree is to use an enum That's not really a great option for a widget library, because it means no custom widgets.
- ekidd 10y agoIn that case, just use Vec<Box<Widget>>, which means "a vector of objects which implement the Widget interface."
- deleted 10y ago[deleted]
- derkha 10y agoBut widgets do have the same type: Widget, which the author already uses as a trait object. I think he was getting confused by mixing &Widget and Rc<RefCell<Widget>>. Just declare a type alias for the latter, use it everywhere, and it should work. You would do the about the same thing in C++, I believe.
- pcwalton 10y agoYes, it does. You can use a trait to provide extensibility.
- mcguire 10y ago"Regarding graphs: The best solution is option 3, using a crate on crates.io (petgraph is the most popular, but rust-forest is fine too)." Or, couldn't you have a vec that owns the nodes and use indices instead of pointers? Or use pointers with the lifetime of the vec?
- pcwalton 10y agoYou could, but petgraph does that for you, so your life will be easier if you use petgraph :)