Pedro G.
Pedro G.

Reputation: 405

Including a module from within another module in Julia

I have a module defined in a file. This Module1 defines a struct and a function that I'm using in my main script. I include this module within another Parent module with include("module1.jl") so that Parent module can use the struct and function in module1. However, I'm having problems with the namespace. Here's an example in a single file:

#this would be the content of module.jl
module Module1
    struct StructMod1
    end
    export StructMod1
    function fit(s::StructMod1)
    end
    export fit
end

module Parent
    #including the module with include("Module1.jl")
    module Module1
        struct StructMod1
        end
        export StructMod1
        function fit(s::StructMod1)
        end
        export fit
    end
    #including the exports from the module
    using .Module1
    function test(s::StructMod1)
        fit(s)
    end
    export test
end

using .Parent, .Module1

s = StructMod1
test(s)



ERROR: LoadError: MethodError: no method matching test(::Type{StructMod1})
Closest candidates are:
  test(::Main.Parent.Module1.StructMod1)

If I remove the mode inclusion in Parent and use Using ..Module1 so that it loads from the enclosing scope, I get this error

ERROR: LoadError: MethodError: no method matching test(::Type{StructMod1})

    Closest candidates are:
      test(::StructMod1) at ...

Upvotes: 1

Views: 508

Answers (1)

David Sainez
David Sainez

Reputation: 6956

In your example, s is a type object not an object of the type StructMod1. In order for s to be the latter, you need to call the constructor for that type. So you should write s = StructMod1() instead of s = StructMod1.

You can read more about types as first class objects here.

Upvotes: 2

Related Questions