Immutability

Composite types are by default immutable. This means that their fields are not changeable after the object is created. Immutability is a good thing as it eliminates surprises when system behavior changes unexpectedly because of data modification. We can easily prove that the concrete Stock type that we created in the last section is immutable:

That's great! Now, the immutability guarantee actually stops at the field level. If the type contains a field and the field's own type is mutable, then changing the underlying data is allowed. Let's try a different example by creating a new composite type called BasketOfStocks, which is used to hold a vector (that is, a one-dimensional array) of stocks and the reason that we are holding them:

struct BasketOfStocks
stocks::Vector{Stock}
reason::String
end

Let's just create an object for testing:

As we already know, BasketOfStocks is an immutable type, so we cannot change any of the fields in it; however, let's see if we can take away one of the stocks from the stocks field:

Here, we just call the pop! function directly on the stocks object, and it will happily take away half of the presents for my wife! Let me repeat—the immutability guarantee does not have any effect on the underlying fields. 

This behavior is by design. The programmer should be cautious about making any assumptions about immutability.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset