我想定义一个简单的类型来表示一个n
包含类型参数的维度形状n
.
julia> struct Shape{n}
name::String
end
julia> square = Shape{2}("square")
Shape{2}("square")
julia> cube = Shape{3}("cube")
Shape{3}("cube")
julia> dim(::Shape{n}) where n = n
dim (generic function with 1 method)
julia> dim(cube)
3
Run Code Online (Sandbox Code Playgroud)
虽然此解决方案确实有效,但它接受非整数值而n
没有问题.
julia> Shape{'?'}("invalid")
Shape{'?'}("invalid")
Run Code Online (Sandbox Code Playgroud)
我最初的想法是n
在struct
声明中使用约束.然而,我认为应该完成的这两种方式似乎都不起作用.
julia> struct Shape{n} where n <: Int
name::String
end
ERROR: syntax: invalid type signature
julia> struct Shape{n<:Int}
name::String
end
julia> Shape{2}("circle")
ERROR: TypeError: Shape: in n, expected n<:Int64, got Int64
Run Code Online (Sandbox Code Playgroud)
我也尝试使用内部构造函数,但这似乎也没有用.
julia> struct Shape{n}
Shape{n}(name) where n <: Int = new(name)
name::String
end
julia> Shape{2}("circle")
ERROR: MethodError: Cannot `convert` an object of type String to an object of type Shape{2}
This may have arisen from a call to the constructor Shape{2}(...),
since type constructors fall back to convert methods.
Stacktrace:
[1] Shape{2}(::String) at ./sysimg.jl:24
Run Code Online (Sandbox Code Playgroud)
我正在使用朱莉娅0.6.0-rc3.0
.
我怎样才能达到理想的行为?
的类型的n
是一种Int
,但它不是一个DataType
是<:Int
.你需要让它在n中,然后@assert typeof(n) <: Int
在构造函数中.
struct Shape{n}
name::String
function Shape{n}(name) where n
@assert typeof(n) <: Int
new(name)
end
end
Shape{2}("square")
Shape{:hi}("square")
Run Code Online (Sandbox Code Playgroud)