How to assign a child tree node to *self?


#1

I was trying to implement a tree in rust. I want to do something like

self = self.children[0]

where self.children is an array of Node.

I try to use Box and Rc to wrap the Node but failed. Is there any way to do it or is it a bad idea implementing a pointer tree in rust? I’ve read some posts and they said we should use array to build a tree instead.


#2

Circular refereces are not welcome in rust. You have to use unsafe or array/vec index to work around rust’s borrow checker.
I believe the tree structure is so common and useful that there are many implementations in crates.io. But none of the general purpose tree libraries suit my need so I wrote yet another crate: trees. Perhaps you can simply use it. Yes it’s a pointer-based implementation. :face_with_raised_eyebrow:
If you are trying to learn rust by implementing a tree library, the very first thing is to design the Node struct.


#3

Like this:

https://play.rust-lang.org/?gist=cd6cdbf258b2196cfb21a7f603f7ac1b&version=stable&mode=debug

Note that you need to remove node from the children array first, because you need to guarantee it won’t be in two places at once.


#4

It seems impossible to walk through a tree by removing its child from its children. Maybe I should consider implementing it in recursive way.