Redefining structs without restart?

I’ll just be so bold as to quote myself (though I’m fairly certain I’ve read something along those lines from other people as well :thinking:)

To expand on that (and not make this shameless self promotion):

Julia has eval (and its macro companion, @eval), which evaluates an Expression at runtime in global scope. Now imagine the following:

struct IntWrapper
   a::Int
end

function increment(a::IntWrapper)
    a.a= + 1
end

function f()
    a = IntWrapper(1)

    # no wait, actually, I want IntWrapper to wrap Floats as well
    @eval struct IntWrapper
        a::Union{Int,Float64}
    end

    b = IntWrapper(5.0) # wait, which Constructor will be called now? And which type will `b.a` have?

   increment(a) # wait, do we print here as well..?
   increment(b)
end

Julia is a compiled language, not interpreted. This means that, when I call f(), the function f as a whole is compiled to machine code. But I have eval code in there that changes the behaviour of the code afterwards while staying in the same function! That’s impossible, so it’s disallowed.

There are more details here, but that’s the gist of it. You could of course change all function calls to make a dynamic lookup in case the definition of the types or the function has changed… but then you lose all benefit of compiling functions in the first place and you’re back to interpreted speeds (which, I’m sure, you also don’t want).

It’s easy to say “why not just do x” and of course you could do x, but that often comes at the cost of things we really want to have, like fast, native, compiled code that can run everywhere. If you insert dynamic lookups at any point that you call a function, writing e.g. GPU kernels is right out (without resorting to a second compiler). There are a lot of design decisions like this, and often there sadly isn’t a straightforward, compact answer why it is that way.


In any case, there have been A LOT of topics on this forum about this and similar things already - you’re not the first to encounter them and won’t be the last. There’s also a lot of issues on the issue tracker, so please do a little more research before pointing to feature X from Y and ask why julia doesn’t do that and that it’ll be just so easy to do.

2 Likes