MutationEdit on GitHub
Value bindings in Grain are immutable, which means that they do not change after they have been declared. While there’s a ton we can get done with regular bindings, it can sometimes be helpful to change the data already associated with a name. We can opt into mutable values by declaring a binding
mut when defined.
Take a look at the following example:
A couple things to note from this example:
- When defining our value binding, we added the
- We can use the value of our mutable binding like any other binding!
- We can also assign values to it using
=and the name will be associated with the new value.
- If we forget
mutbut try to assign to the binding, we’ll get a type error.
When using mutable values that are
Numbers, we can use some built-in operators to make working with them easier. Grain provides
%=, which perform the math operation on the value and re-assign the result.
These operators return
void to help alleviate ambiguity and make code easier to understand—use the name of the binding to get its current value.