Import struct without changing its "scope"

Yue-Zhengyuan
Tue, 21 Nov 2023 14:12:59 +0000
New to Julia

I have problems on importing struct from other files. Suppose I have the file structure:

- Lattices.jl
- Hamiltonians.jl
- main.jl

Lattices.jl defines a struct called Lattice:

module Lattices
export Lattice

struct Lattice
    lx::Int64
    ly::Int64
end
end

Hamiltonians.jl defines Hamiltonian on a Lattice:

module Hamiltonians
export Hamiltonian

include("Lattices.jl")
using .Lattices

struct Hamiltonian
    lat::Lattice
    coeffs::Vector{Float64}
end
end

main.jl tries to create a Hamiltonian:

include("Lattices.jl")
include("Hamiltonians.jl")
using .Lattices
using .Hamiltonians

a = Lattice(16, 16)
ham = Hamiltonian(a, [1.0, 0.0])
display(ham)

However, I get the error

ERROR: LoadError: MethodError: Cannot `convert` an object of type Lattice to an object of type Main.Hamiltonians.Lattices.Lattice

So the problem is that when I import Lattice into the Hamiltonians module, its “scope” is also changed (sorry if I am not using the correct terminology; I come from Python so I have never encountered such behavior before). It is no longer regarded as the same Lattice from Lattices.jl. How do I tell Julia that different Lattice’s are the same thing?

8 posts - 3 participants