How to self reference a struct

How do you define an array in a struct of itself?

julia> mutable struct node
children::Array{node, 3}
ERROR: invalid redefinition of constant node
[1] top-level scope
@ REPL[5]:1

Interesting, I guess the following would work:

abstract type AbstractNode end
struct Node{T<:AbstractNode}<:AbstractNode

But I think you’d never be able to instantiate this since you can’t use leaf nodes, or they can’t be null. You probably want to use a union or something to make it practical.

EDIT: As stated below, an empty array is perfectly fine, so there’s not an issue with instantiation.

1 Like

That should work, I’ve done such constructs a number of times - do you perhaps already have something called node in that session? That’s what the error suggests, at least. What do you get in a new session?

Also, please quote your code, to make it easier to help you.

You can use that - leaves just don’t have children, the array is empty. You can even have a parent field too - if the parent is equal to the object itself, you’re at the root. It’s also a bit more efficient to do it this way, since there’s no type instability involved anymore, unlike with the union approach.


I think that may have been the case. Thank you so much for your help. Closing.