Struct julia结构内部构造函数可选类型规范

Struct julia结构内部构造函数可选类型规范,struct,types,constructor,julia,Struct,Types,Constructor,Julia,考虑以下结构: struct MyType1{T} data::T end 它可以通过两种方式进行实例化: println(MyType1(5)) # MyType1{Int64}(5) println(MyType1{Int}(5)) # MyType1{Int64}(5) 当我定义与内部构造函数类似的内容时: struct MyType2{T} data::T MyType2(x::T) where T = n

考虑以下结构:

struct MyType1{T}
    data::T
end
它可以通过两种方式进行实例化:

println(MyType1(5))                 # MyType1{Int64}(5)
println(MyType1{Int}(5))            # MyType1{Int64}(5)
当我定义与内部构造函数类似的内容时:

struct MyType2{T}
    data::T
    MyType2(x::T) where T = new{T}(x)
end

struct MyType3{T}
    data::T
    MyType3{T}(x::T) where T = new{T}(x)
end
struct MyType4{T}
   data::T
   MyType4{T}(x::T) where T = new{T}(x)
end

MyType4(x::T) where T = MyType4{T}(x)
我只能用一种方式实例化它们:

println(MyType2(5))                 # MyType2{Int64}(5)
println(MyType2{Int}(5))            # MethodError

println(MyType3(5))                 # MethodError
println(MyType3{Int}(5))            # MyType3{Int64}(5)
如何使内部构造函数中的类型规范成为可选的(在上面的示例中,使
MyType2
MyType3
不抛出
MethodError


julia版本1.4.1

只需提供一个额外的构造函数:

struct MyType2{T}
    data::T
    MyType2(x::T) where T = new{T}(x)
end

struct MyType3{T}
    data::T
    MyType3{T}(x::T) where T = new{T}(x)
end
struct MyType4{T}
   data::T
   MyType4{T}(x::T) where T = new{T}(x)
end

MyType4(x::T) where T = MyType4{T}(x)
试验