Avoiding redefinition of structs

I have a basic question about including .jl files that I have created myself. I have a file BinaryTree.jl which stores a struct BinaryTree and some associated routines. In whichever file I have to use this data structure, I have included the command
include("BinaryTree.jl");
However, in more than one such file is run, this command is executed more than once, and I get the error

LoadError: invalid redefinition of constant BinaryTree

Could you suggest how I can avoid redefinition ? I don’t see an option but to include BinaryTree.jl in every file where it is needed, as this inclusion has to be independent of whether other files have included this data structure or not.

On a related note, is there a way of avoiding repeated loading of routines if a file, say for example f.jl, is included more than once during runtime ?

You shouldn’t have include("BinaryTree.jl") everywhere it gets used. You should consider using a module for it. Alternatively, if you simply put include("BinaryTree.jl") somewhere near the beginning of your module or script or whatever you’re working on, you shouldn’t need to worry about it.

2 Likes

I agree with @ExpandingMan that you should probably use a module instead. But if you still want a quick-fix, you could use something like

@isdefined(BinaryTree) || include("BinaryTree.jl")
1 Like

Thank you very much, I will read about this structure.

1 Like

Thanks !