Mutation
Edit on GitHubValue 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.
Using mut
Take a look at the following example:
A couple things to note from this example:
- When defining our value binding, we added the
mut
keyword. - 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
mut
but try to assign to the binding, we’ll get a type error.
Working with Mutable Numbers
When using mutable values that are Numbers
, we can use some built-in operators to make working with them easier. Grain provides +=
, -=
, *=
, /=
, and %=
, which perform the math operation on the value and re-assign the result.
These operators also return the assigned result, so you can use the new value immediately.