How to define a nested type?

For example: a nested dict with unknown depth.


I have tried this:


But it gives “UndefVarError: Tree not defined”
(I want to use this tree to develop a lexer)


I had the exact same problem recently, and the issue here is that whilst Julia does support recursive type declarations, this doesn’t work with type aliases (which is what you’re doing).

In the case of a type alias (e.g. const MyTypeName = SomeOtherType), Julia sees these as a regular assignment and so won’t allow you to assign something on the RHS to the LHS before the RHS value has first been declared.

A regular recursive type declaration however will work, so something like eg:

struct Tree
    child::Dict{Char, Union{Int, Tree}}

is fine and dandy. And I’m sure you can modify this kind of structure into something that works for you.

(I get that it’s a little less elegant than a straight dictionary, but you can add some methods onto Tree to pass on down into the dictionary and have it behave as you want).