Redefine Struct when working with REPL

Hi,

I would like to use structs to bundle values in a way similar to pure OOP.

So I would create a struct to encapsulate the relevant attributes.

Down below is an example:

struct Lion
    maneColor::String
    roar::String
    weight::Int # Do some work and then realize I need this attribute
end

alion = Lion("yellow", "rar")
# Redefine the line after realizing I need the weight attribute in the struct
alion = Lion("yellow", "rar", 10) 

The REPL doesn’t let me redefine the struct as it throws an error:
ERROR: LoadError: invalid redefinition of constant Lion

I already had a look at the Revise.jl package (https://timholy.github.io/Revise.jl/stable/#Other-Revise-workflows-1) but didn’t get it to work ( it installed alright without an error, but it doesn’t let me revise my code automatically either).

My question ultimately is how/what to use Julia/Atom/REPL in order to redefine certain functions/structs without having to restart the Julia client all over again.

Thanks in advance!

Personally I’ve found that my structures don’t change too often, mostly it’s the code that is changing, so when I’ve (rarely) needed to change the structures I just do a stop/start of Julia inside atom.

If your structures are changing often then you can place them in a module like:

module Data
    struct Lion
        maneColor::String
        roar::String
        weight::Int # Do some work and then realize I need this attribute
    end
end

When you rerun the script you will get a warning that Data was redefined, which you can ignore. However Data.Lion will now be the new data object.

2 Likes

The short answer is that you can’t redefine a struct. If you are playing with different structure layouts, and you don’t need to dispatch off their parametric types, you can use named tuples. For instance alion = (maneColor = "yellow", roar = "rar", weight = 10).

If you want the sugar of a typed named tuple, I registered ProtoStructs.jl for that.

2 Likes

Thank you for the recommendations and answers!
I’ll have a look into the different options.

Just to clarify from your OP, not being able to redefine structs does not mean Revise isn’t working, this is expected behaviour - try changing a function definition in an included file in your code to see that (in all likelihood) it is working.

As for the struct issue itself, in addition to the answers above people also often simply create multiple structs MyStruct1, MyStruct2 etc as they go along, and finally rename to MyStruct when they’ve settled on a definition they’re happy with.

1 Like

Unfortunately it is not something the language allows at the moment. See the issues linked in