Declare the size of an array attribute in a type definition

后端 未结 1 891
夕颜
夕颜 2021-01-11 16:55

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 len         


        
相关标签:
1条回答
  • 2021-01-11 17:30

    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
    

    And then from 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])
    
    0 讨论(0)
自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题