Variables in Sway are immutable by default. This means that, by default, once a variable is declared, its value cannot change. This is one of the ways how Sway encourages safe programming, and many modern languages have this same default. Let's take a look at variables in detail.

Declaring a Variable

Let's look at a variable declaration:

let foo = 5;

Great! We have just declared a variable, foo. What do we know about foo?

  1. It is immutable.
  2. Its value is 5.
  3. Its type is u64, a 64-bit unsigned integer.

u64 is the default numeric type, and represents a 64-bit unsigned integer. See the section Built-in Types for more details.

We can also make a mutable variable. Let's take a look:

let mut foo = 5;
foo = 6;

Now, foo is mutable, and the reassignment to the number 6 is valid. That is, we are allowed to mutate the variable foo to change its value.

Type Annotations

A variable declaration can contain a type annotation. A type annotation serves the purpose of declaring the type, in addition to the value, of a variable. Let's take a look:

let foo: u32 = 5;

We have just declared the type of the variable foo as a u32, which is an unsigned 32-bit integer. Let's take a look at a few other type annotations:

let bar: str[4] = "sway";
let baz: bool = true;

If the value declared cannot be assigned to the declared type, there will be an error generated by the compiler.

Configurable Constants

Configurable constants are special constants that behave like regular constants in the sense that they cannot change during program execution, but they can be configured after the Sway program has been built. The Rust and TS SDKs allow updating the values of these constants by injecting new values for them directly in the bytecode without having to build the program again. These are useful for contract factories and behave somewhat similarly to immutable variables from languages like Solidity.

Configurable constants are declared inside a configurable block and require a type ascription and an initializer as follows:

configurable {
    U8: u8 = 8u8,
    BOOL: bool = true,
    ARRAY: [u32; 3] = [253u32, 254u32, 255u32],
    STR_4: str[4] = "fuel",
    STRUCT: StructWithGeneric<u8> = StructWithGeneric {
        field_1: 8u8,
        field_2: 16,
    ENUM: EnumWithGeneric<bool> = EnumWithGeneric::VariantOne(true),

At most one configurable block is allowed in a Sway project. Moreover, configurable blocks are not allowed in libraries.

Configurable constants can be read directly just like regular constants:

    fn return_configurables() -> (u8, bool, [u32; 3], str[4], StructWithGeneric<u8>) {
        (U8, BOOL, ARRAY, STR_4, STRUCT)