Skip to content

Mutability

Apoorv Singal edited this page Aug 29, 2020 · 1 revision

Variables in Volant are mutable by default, but they can be made immutable by using the const keyword with types. For example, a: const u8 = 0; declares a as immutable and re-assignments to the variable are disallowed by the compiler.

const can also be used in compound types to make their specific parts constant. For example, declaring a variable as var: * const u8 = aPtr; allows you to assign to var (var = anotherPointer;) but forbids you from assigning to the value var points to, i.e, *var = x; will throw a compile-time error. The same goes for arrays, vectors, maps, and structs.

You can typecast a non-constant value to a const value to make it immutable, but typecasting a constant value to non-constant is not allowed. For example, you cannot pass a constant value as an argument to a function that accepts a non-constant value, but you can pass a non-constant value to a function that accepts a constant value.

const does not ensure that the data of a block of memory will remain constant throughout the code, it only means that the current reference to the value does not have the permission to modify it, some other parts of code may still be able to modify it.

Enums are always constants.

Clone this wiki locally