Reputation: 175
I do not get the difference between the following two struct definitions. The first works without any problems, while the second gives a Type Error:
julia> struct point1
xy::Vector{Float64}
end
julia> struct point2
xy::Array{Float64,1}(2)
end
ERROR: TypeError: point2: in type definition, expected Type, got Array{Float64,1}
Stacktrace:
[1] eval(::Module, ::Any) at ./boot.jl:235
[2] eval(::Any) at ./boot.jl:234
[3] macro expansion at /Users/.julia/v0.6/Atom/src/repl.jl:186 [inlined]
[4] anonymous at ./<missing>:?
Any ideas?
Upvotes: 1
Views: 272
Reputation: 10157
The issue here is that Array{Float64,1}(2)
isn't a type (i.e. typeof(Array{Float64,1}(2)) != DataType
) but a newly initialized instance of a Array{Float64,1}
.
If you would like to fix the dimension of the array field xy
you can
1) make constructors throw errors/warnings if someone tries to initialize with an array of wrong size (this doesn't effect performance of course)
2) use StaticArrays.jl to maybe speed up your code
Pkg.add("StaticArrays")
using StaticArrays
struct point3
xy::SVector{2,Float64}
end
Test:
julia> p = point3(@SVector rand(2))
point3([0.621778, 0.083348])
julia> p = point3(rand(2))
point3([0.737558, 0.405582])
julia> p = point3(rand(3))
ERROR: Dimension mismatch. Expected input array of length 2, got length 3
Upvotes: 4
Reputation: 175
Solved it:
struct point2
xy::Array{Float64,1}
end
The problem was the definition of the dimension ...
Upvotes: 0