구조체와 fit () 함수를 정의하는 Module1 모듈이 있다고 가정 해 보겠습니다. Module1을 포함하고 fit ()를 호출하는 test () 함수를 정의하는 다른 모듈 인 Parent라고합니다. 모듈 1에서 구조를 정의한 다음 부모에서 test ()를 호출하면 네임 스페이스에 문제가 있습니다. 이 예제의 코드는 다음과 같습니다.
#this module would be in a separate file
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)
return s
end
export test
end
using .Parent, .Module1
s = Parent.Module1.StructMod1()
@show test(s)
s2 = StructMod1()
@show test(s2)
그리고 출력
test(s) = Main.Parent.Module1.StructMod1()
ERROR: LoadError: MethodError: no method matching test(::StructMod1)
Closest candidates are:
test(::Main.Parent.Module1.StructMod1)
또는 .Module1 사용을 ..Module1 사용으로 바꾸면 s2 정의가 작동합니다. 하지만 .Parent를 사용하여 호출 할 때 Module1이 이미로드되었는지 확인해야합니다.
하나의 모듈로 구조체를 정의한 다음 다른 모듈의 함수와 함께 사용하는 가장 좋은 방법은 무엇입니까?
이중 포함으로 인해 오류가 발생합니다. 귀하의 예 Parent.Module1
에서은 Module1
. include
멍청한 복사 / 붙여 넣기로 생각하는 것이 유용합니다 . 동일한 소스 파일을 공유하더라도 이중 포함은 두 개의 다른 모듈로 표시되도록합니다 (예제에서 볼 수 있음).
해결책은 include
한 번만 모듈을 참조하기 위해 상대 가져 오기 를 사용하는 것입니다.
전체 모듈 세트를 구성하는 include
경우 메인 모듈의 모든 모듈을 순차적으로 선호하고 필요한 경우 상대 가져 오기를 사용합니다. 나는 이것이 가장 간단한 접근 방식이라고 생각합니다.
최종 버전은 다음과 같습니다.
# Module1.jl
module Module1
struct StructMod1
end
export StructMod1
function fit(s::StructMod1)
end
export fit
end
# Parent.jl
module Parent
using ..Module1
function test(s::StructMod1)
fit(s)
return s
end
export test
end
#Main.jl
include("Module1.jl")
include("Parent.jl")
using .Parent, .Module1
s = Parent.Module1.StructMod1()
@show test(s)
s2 = StructMod1()
@show test(s2)
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다