Need some help with tree and methods

Hello, I've wrote some really basic pointer based tree using Rc and RefCell:

But in this example all functions take the pointer as first argument, and the data as the second. Which is very C-style, and I can accidentally pass wrong node as first parameter. I would like to convert this code to use methods, thus taking self as first argument, but the problem is that I expect a pointer, and I can't write impl for Rc<RefCell<Node<T>>>, only for Node<T> in which case self would be Node<T>. Any general advice? I've tried using plain self and return Node<T> but this leads to some ownership problems.

Thanks!

When values of type Rc<RefCell<T>> are exposed, users are generally assumed to be calling .borrow() or .borrow_mut() and therefore the API delegates the responsibility of correct usage (i.e. not borrowing mutably and immutably at the same time or borrowing mutably multiple times).

If you want (and can) provide additional guarantees and enforce correct usage, you can still continue writing free functions that take Rc<RefCell> as their first parameter. It's not "very C-style", I have no idea where you got that idea from. Methods are just syntactic sugar. They are neither the beginning nor the end of "good style" or idiomatic Rust.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.