'Foo'没有匹配Foo的方法(:: Bar)

Jam*_*ook 1 julia

我想开始,我无法在代码的精简版本中重新创建我的问题.下面的代码按预期工作,所以这篇文章可能没有很好地提出.扩展代码太长而无法在此发布,但失败了.我将描述我正在尝试做什么,因为它可能会帮助其他人.

我创建了三种类型:Bar,Baz和Qux,它们包含Bar和Baz上的方法foo.我创建一个qux并查询它的foo

qux = Wubble.Qux()
qux.foo
Run Code Online (Sandbox Code Playgroud)

我按预期得到以下两种方法:

foo(bar::Bar)
foo(baz::Baz)
Run Code Online (Sandbox Code Playgroud)

然后,当我尝试使用bar或baz实际使用qux.foo时,它会给我一个错误'foo' has no method matching foo(::Bar).

遗憾的是,我无法使用精简代码重新创建此错误,并且实际代码不具有吸引力.在我错过的场景中,有多种方法可以解决此错误?它可能与方法扩展和函数阴影有关,就像在这篇文章中,但我无法修复.

module Wibble
type Bar
  data::Number
  function Bar(num::Number=0)
    this = new(num)
    return this
  end
end
end

module Wobble
type Baz
  data::String
  function Baz(vec::String="a")
    this = new(vec)
    return this
  end
end
end

module Wubble
using Wibble
using Wobble
typealias Bar Wibble.Bar
typealias Baz Wobble.Baz

type Qux
  foo::Function
  function Methods(this::Qux)
    function foo(bar::Bar)
      println("foo with bar says ", bar.data)
    end
    function foo(baz::Baz)
      println("foo with baz says ", baz.data)
    end
    this.foo = foo
    return this
  end
  function Qux()
    this = new()
    this = Methods(this)
    return this
  end
end

end
Run Code Online (Sandbox Code Playgroud)

Sim*_*rne 7

我不确定会出现什么问题,但有几点可能会有所帮助

  • 你几乎从不想Function在某种类型中使用字段:这是来自"基于点的"OOP语言的人们常见的惯用错误.Julia方法是通用的,不属于特定类型.这样做没有任何好处,不仅更令人困惑(你有很多嵌套级别来编写可以用2行写的东西),但它可能使编译器更难以推断类型,影响性能.

  • 你应该使用import Wibble.Bar而不是typealias.如果你使用它,你不需要using.

  • 外部构造函数更容易用于指定默认参数.

简而言之,我的版本将是:

module Wibble
type Bar
  data::Number
end
Bar() = Bar(0)
end

module Wobble
type Baz
  data::String
end
Baz() = Baz("a")
end

module Wubble
import Wibble.Bar
import Wobble.Baz

qux(bar::Bar) = println("foo with bar says ", bar.data)
qux(baz::Baz) = println("foo with baz says ", baz.data)

end
Run Code Online (Sandbox Code Playgroud)