Understanding immutable composite types with fields of mutable types in Julia

爷,独闯天下 提交于 2019-12-05 02:10:22

So here is something mind bending to consider (at least to me):

julia> immutable Foo
         data::Vector{Float64}
       end

julia> x = Foo([1.0, 2.0, 4.0])
Foo([1.0,2.0,4.0])

julia> append!(x.data, x.data); pointer(x.data)
Ptr{Float64} @0x00007ffbc3332018

julia> append!(x.data, x.data); pointer(x.data)
Ptr{Float64} @0x00007ffbc296ac28

julia> append!(x.data, x.data); pointer(x.data)
Ptr{Float64} @0x00007ffbc34809d8

So the data address is actually changing as the vector grows and needs to be reallocated! But - you can't change data yourself, as you point out.

I'm not sure there is a 100% right answer is really. I primarily use immutable for simple types like the Complex example in the docs in some performance critical situations, and I do it for "defensive programming" reasons, e.g. the code has no need to write to the fields of this type so I make it an error to do so. They are a good choice IMO whenever the type is a sort of an extension of a number, e.g. Complex, RGBColor, and I use them in place of tuples, as a kind of named tuple (tuples don't seem to perform well with Julia right now anyway, wheres immutable types perform excellently).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!