liveBook · Manning

Mutable object

As explained in Julia as a Second Language

A mutable type is a Julia type whose instances can have their fields modified after creation.

A mutable object has fields that can be changed after it is created. In Julia, declare a composite type with `mutable struct` to allow field assignment; a plain `struct` is immutable by default. section 7.3.2 section 7.5

Track an archer’s arrows

A battle simulation needs to update an archer’s remaining arrows: mutable struct Archer arrows::Int end function shoot!(archer::Archer) if archer.arrows > 0 archer.arrows -= 1 end archer end archer = Archer(24) shoot!(archer) # Archer(23) The guard prevents the arrow count from dropping below zero. The `!` signals mutation by convention; it does not itself make the object mutable. Returning the changed object makes its new state easy to inspect at the REPL. section 7.3.2

Immutability can reduce the likelihood of bugs by preventing field changes. Choose mutability when the object needs to represent changing state, rather than adding it automatically. section 7.3.2

Listing 12.29 Adding a stage to the bottom
function pushfirst!(ship::SpaceVehicle, r::StagedRocket)
    r.nextstage = ship.activestage    #1
    ship.activestage = r              #2
    ship
end

A linked rocket-stage example uses field assignments to connect a new stage and update the vehicle’s active stage. section 12.6.1

Changing a type definition, such as converting a `struct` to a `mutable struct`, requires restarting the Julia REPL: type definitions cannot be modified at runtime. section 12.6.1

How Julia as a Second Language covers it

How deep it goes
Explains mutable declarations, field assignments, mutation naming conventions, REPL-friendly returns, and the need to restart after changing a type definition.
Examples
Demonstrates archers spending arrows and rocket stages being added to or removed from a vehicle.
What you can do after
Apply it in Julia to implement state-changing methods and linked-stage collection operations.
How it connects
Connects mutable objects to composite types, immutable objects, methods, and linked lists.

Also explained in

Compare how 5 books explain mutable object →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Julia as a Second Language. The section links point to the parts of the book it draws on.