Michael Hewson
Michael Hewson

Reputation: 1534

Can you have types that refer to each other in Julia?

I get ERROR: LoadError: UndefVarError: Expression not defined for the following code:

struct IntLiteral
    value::Int
end

struct Plus
    left::Expression
    right::Expression
end

struct Minus
    left::Expression
    right::Expression
end

const Expression = Union{IntLiteral, Plus, Minus}

If I declare Expression ahead of Plus and Minus, I get a similar error. Wrapping the code in a module doesn't change anything, either.

Is there a way to reference a type ahead of its declaration in Julia? If not, what is the recommended solution for cases like this, where two types depend on each other? Just remove the type annotations?

In this particular case, I believe I could make Expression an abstract type, and have the others be subtypes of it. Is that recommended in this case? What about the general case?

Upvotes: 0

Views: 370

Answers (1)

mbauman
mbauman

Reputation: 31342

Not currently, no. See issue #269 for more details.

Upvotes: 1

Related Questions