我想定义一个简单的类型来表示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
虽然此解决方案确实有效,但它接受n
的非整数值且没有问题。
julia> Shape{'?'}("invalid")
Shape{'?'}("invalid")
我最初的想法是在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
我也尝试过使用内部构造函数,但这似乎也没有用。
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
我正在使用Julia 0.6.0-rc3.0
。
如何实现理想的行为?
答案 0 :(得分:5)
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")