是否可以从抽象类型 julia 之外的其他类型继承?

Ale*_*aev 3 julia

我有一个无法更改的函数,并且它需要 type ExpectedType

function some_function(some_parameter::ExpectedType)
   ....
   some implementation
   ....
end
Run Code Online (Sandbox Code Playgroud)

我想传递我的 type 对象OtherType

我决定OtherType继承ExpectedType.

struct OtherType <: ExpectedType end
Run Code Online (Sandbox Code Playgroud)

但我收到一个错误:ERROR: invalid subtyping in definition of OtherType

  1. 是否可以从非abst类型继承?
  2. 我怎样才能获得我需要的功能?

Bog*_*ski 6

  1. 不可能从非抽象类型继承。
  2. 我通常会做的是编写一个构造函数作为ExpectedType参数OtherType,然后调用some_function(ExpectedType(your_object))

然后你也可以定义:

SourceModuleName.some_function(x::OtherType) = some_function(ExpectedType(x))
Run Code Online (Sandbox Code Playgroud)

这样您就不必显式调用构造函数。