为什么朱莉娅子模块的功能被遮蔽了?

发布于 2025-02-03 18:53:10 字数 399 浏览 2 评论 0原文

考虑以下代码:

module Foo
export g, h

  module Bar
  export f

  f(::Int) = 2

  end

using .Bar

f(::String) = "abc"

g() = f("a")
h() = f(12)

end

当我运行此程序时,如果我尝试调用g(),我会按预期获得“ ABC”。如果我调用h()我会收到一个错误消息。不知何故,f(:: int)的定义正在被遮蔽。那应该发生吗?如何解决这个问题?

如果我省略了f(:: string)的定义,则h() works。

Consider the following code:

module Foo
export g, h

  module Bar
  export f

  f(::Int) = 2

  end

using .Bar

f(::String) = "abc"

g() = f("a")
h() = f(12)

end

When I run this, if I try calling g() I get "abc" as expected. If I call h() I get an error message. Somehow, the definition of f(::Int) is being shadowed. Is that supposed to happen? How to fix this?

If I omit the definition of f(::String) then h() works.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

×眷恋的温暖 2025-02-10 18:53:10

是的,这是正确的行为。为了扩展方法,应该导入( https://docs.julialang.org/en/v1/manual/momodules/#using-and-import-with-with-with-with-specific-sendifiers--and-sendifiers-and-and-adding-methods

因此,正确的示例应该看起来像这样:

module Foo
export g, h

  module Bar
  export f

  f(::Int) = 2

  end

using .Bar
import .Bar: f

f(::String) = "abc"

g() = f("a")
h() = f(12)

end

我添加了import .bar:f,因为bar可以导出其他不想扩展的名称。因此,将这两个混合在一起是可以的。随着此添加,一切都按预期工作

julia> using .Foo

julia> g()
"abc"

julia> h()
2

Yes, this is correct behaviour. In order to extend method it should be imported (https://docs.julialang.org/en/v1/manual/modules/#using-and-import-with-specific-identifiers,-and-adding-methods)

So, correct example should look like this:

module Foo
export g, h

  module Bar
  export f

  f(::Int) = 2

  end

using .Bar
import .Bar: f

f(::String) = "abc"

g() = f("a")
h() = f(12)

end

I've added import .Bar: f because Bar can export other names, which you do not want to extend. So it is fine to mix these two together. With this addition, everything is working as intended

julia> using .Foo

julia> g()
"abc"

julia> h()
2
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文