Assignments are statements that set the value of a field to the result of the evaluation of an expression.
In Fuzion, static code analysis ensures that no fields are called before an initial value has been assigned to the field.
A program that may access uninitialized fields does not compile:
Fields in Fuzion by default are immutabe, i.e., no value may be assigned to a field except for the assignment of the initial value. For most situations, it is fully sufficient to work with immutable fields.
Imagine you want to write a loop that calculates the sum of all the elements
in array by iterating over the array and adding up the values of all elements in
sum. The following code does this using an immutable
loop index variable:
This code, in effect, creates a new instance of
sum for each
loop iteration. Each of these instances is immutable.
CAVEAT: Using mutable fields has a number of disadvantages, in particular, the field may no longer be used by multiple threads and functions accessing that field become impure, i.e., their result depends not only of the input parameters but also on the current value of the mutable field. This makes analysis of the code hard and prohibits optimizations that otherwise would be possible.
Mutable fields can be realized in Fuzion using effects, in particular
mutate effect permits repeated modification of a value. A
x that may be mutated using this effect can be created via a
mut giving the intial value
a of the
If you analyse this code using the button Effects!, you will see that
this code uses the
Once created, the field may be updated to a value
x <- b
To read the field,
x.get is currently required (it is planned to
add syntax sugar to avoid the need to call
.get explicitly). This
small code-snippet illustrates this:
A more useful example using a mutable field
cn to cache the
result of a function call is given here:
The following sections of this tutorial will present techniques to avoid field updates. Using these techniques will enable compiler optimizations that are not possible with mutable fields. Immutable fields will also be a basic prerequisite for Fuzion's safe concurrency model.