-
Notifications
You must be signed in to change notification settings - Fork 2
Mutable variables
Mutable variables are an important aspect of Plume programming. They allow you to store values that can be updated after their declaration. This is useful when you need to store a value that may change over time.
To declare a mutable variable, you need to use the mut
keyword followed by the variable name and its type. Here's an example:
// Declare a mutable variable named `my_variable` of type `int` and assign the value `42` to it
mut my_variable: int = 42
In this example, we have declared a mutable variable named my_variable
of type int
and assigned the value 42
to it.
You can update the value of a mutable variable by using the assignment operator. Here's an example:
// Update the value of the variable `my_variable`
my_variable = 43
When updating the value of a mutable variable, you need to ensure that the new value is of the correct type. If you try to update a mutable variable with a value of a different type, you will get a type error.
When declaring a mutable variable, you can't make it depend on locally quantified type variables: meaning you can't mix generics with mutable variables.
However, you can declare a mutable variable with a generic type if the generic type is globally quantified.
In Plume, variables are passed by value by default. This means that when you pass a variable to a function, the function receives a copy of the variable, not the original variable itself. This ensures that the original variable remains unchanged.
But you can override this behavior by passing a variable by reference. This allows the function to modify the original variable. To pass a variable by reference, you need to have it defined as a mutable variable and make the function take a mutable variable to it.
Here's an example:
fn update<A>(mut x: A, value: A): unit {
x = value
return unit
}
mut my_variable: int = 42
println(my_variable.show()) // This will print `42`
update(my_variable, 43)
println(my_variable.show()) // This will print `43`
Declaring a function argument as a mutable variable is done by prefixing the argument name with the mut
keyword. This allows the function to take full control of the variable and update its value.