Import struct to module

I am trying to create modules that contains functions and structs

struct coord{T,N}
    x::T 
    y::N
end 

module A
function ms(pt::coord)
    println(pt.x)
end
end

Getting this error when I run test

UndefVarError: coord not defined

How to import coord in a module?

You should define Coord inside the same module, or else define it in a separate module and then do using or import to import that module.

1 Like

Here is an example of David’s note.

julia> module Coordinates

       export Coord, distance_from_origin
       #=
            The parameter `T` will be replaced by the type
            used to hold the values of `x` and `y`. 
            Presumably, you want the `x` and `y` of one coordinate
            to share a single type (maybe Float64 or Int32).

            When you construct an actual Coord with Float64 values,
            this happens:

            julia> point = Coord(1.0, 3.0)
            Coord(1.0, 3.0)
            julia> point.y
            3.0
       =#
       struct Coord{T}
           x::T 
           y::T 
       end 

       function distance_from_origin(point::Coord{T}) where {T}
           return sqrt(point.x * point.x + point.y * point.y)
       end

end # module Coordinates
Main.Coordinates

Now you can use what you have placed in that module.
(note that when using a module you typed into the interactive shell, you say:
using .Coordinates but when using a module that is a saved package, you say:
using Coordinates without the dot).

julia> using .Coordinates

julia> point = Coord(4.0, 2.0)
Coord{Float64}(4.0, 2.0)

julia> point.x, point.y
(4.0, 2.0)

julia> distance_from_origin(point)
4.47213595499958
2 Likes