Exporting structs and functions

Hi,
I am having a little trouble when exporting Structs and functions across several julia files.

Here is an example

# --- agent_type.jl ---
module Agent_Type

using Agents: AbstractAgent

export Casualty
mutable struct Casualty <: AbstractAgent
    id :: Int
    pos :: Tuple{Int,Int}
    trauma :: Int
    rescued :: Bool

    function Casualty(id,pos;trauma=2,rescued=false)
        new(id,pos,trauma,rescued)
    end

end
end
# --- ammend_props.jl ---
module Ammend_Props
    include("agent_type.jl")
    using .Agent_Type: Casualty

    function ammend_cas_properties(cas::Casualty, val::Any)
        cas.rescued = val
        return cas
    end

end
# -- main.jl ---
begin
    using Pkg
    Pkg.activate(joinpath(homedir(),"workspace","julia","envs","agentsenv"))
end


include("agent_type.jl")
include("ammend_props.jl")

using .Agent_Type: Casualty
using .Ammend_Props: ammend_cas_properties

cas1 = Casualty(1, (7,7), trauma = 3)

ammend_cas_properties(cas1, true)
>>>
ERROR: MethodError: no method matching ammend_cas_properties(::Casualty, ::Bool)
Closest candidates are:
  ammend_cas_properties(::Main.Ammend_Props.Agent_Type.Casualty, ::Any) at ~/github/CRTT-lite/test/ammend_props.jl:5
Stacktrace:
 [1] top-level scope
   @ ~/github/CRTT-lite/test/test_main.jl:15

Any particular way I can avoid this by exporting Casualty instead of Main.Ammend_Props.Agent_Type.Casualty

The short answer is that you need to include each file exactly once. Including a file multiple times (once via ammend_props.jl and again via main.jl) creates completely different types and functions that happen to have the same names, which is never what you want. I posted a few relevant answers back on this older thread that might be helpful: Modules and namespaces - #5 by rdeits

In your case, you could delete include("agent_type.jl") from Ammend_Props and instead just do using ..AgentType: Causality (note the .. instead of . since you’d be referring to the AgentType module in the parent Main.

4 Likes