朱莉娅类型与抽象类型和definied类型

时间:2017-04-08 14:04:21

标签: types julia abstract

如何使用一个抽象字段和一个定义字段来创建类型

像这样:

abstract AbstractType 

type type1 <: AbstractType
    x
    y
end

type type2 <: AbstractType
    w 
    z 
end

type MyType{T<:AbstractType}
         a::T
         b::Int64
 end

a = MyType(type1(1,2))

我尝试了一些构造函数,但它也没有用。

2 个答案:

答案 0 :(得分:4)

It's not clear what you're trying to do. The reason your last statement isn't working has less to do with mixed types and more to do with the fact that you're trying to instantiate your type while missing an input argument.

If you want to be able to instantiate with a default value for b, define an appropriate wrapper constructor:

abstract AbstractType
type type1 <: AbstractType; x; y; end
type type2 <: AbstractType; w; z; end
type MyType{T<:AbstractType}; a::T; b::Int64; end
MyType{T<:AbstractType}(t::T) = MyType(t,0);   # wrapper

julia> a = MyType(type1(1,2))
  MyType{type1}(type1(1, 2), 0)

答案 1 :(得分:1)

您需要MyType成为只包含一个字段的类型,并允许该字段保存type1(或两个)。那就是:

type MyType{T<:AbstractType}
         a::T
end