本文介绍了在类型定义中声明数组属性的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我目前有一个带有数组属性的类型
I currently have a type with an array attribute
immutable foo
a::Int64
b::Int64
x::Array{Float64,1} # One dimension array of Float 64, but no length info
end
我知道该数组将始终包含100个Float64元素.有没有一种方法可以在类型注释中传递此信息?也许类似于可以声明实例化数组的大小的方法,例如x = Array(Float64, 100)
?
I Know that the array will always contain 100 Float64 elements. Is there a way to pass this information in the type annotation? Perhaps something similar to the way one can declare the size of an instantiated array like x = Array(Float64, 100)
?
推荐答案
您可以使用内部构造函数强制执行不变式.
You can enforce invariants with an inner constructor.
immutable Foo
a::Int64
b::Int64
x::Vector{Float64} # Vector is an alias for one-dimensional array
function Foo(a,b,x)
size(x,1) != 100 ?
error("vector must have exactly 100 values") :
new(a,b,x)
end
end
然后从REPL:
julia> Foo(1,2,float([1:99]))
ERROR: vector must have exactly 100 values
in Foo at none:7
julia> Foo(1,2,float([1:100]))
Foo(1,2,[1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0,10.0 … 91.0,92.0,93.0,94.0,95.0,96.0,97.0,98.0,99.0,100.0])
这篇关于在类型定义中声明数组属性的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!