Variables

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.

Configuration-time Constants

It is possible to define and initialize constant variables in the manifest file Forc.toml of a Sway project. These constants then become visible and usable in the corresponding Sway program. Such variables are called configuration-time constants and have to be defined in their own section called [constants] in the manifest file. The syntax for declaring such constants is as follows:

[constants]
some_contract_addr = { type = "b256", value = "0x580acb6ee759d9be0c0f78d3ef24e1b59300c625b3c61999967366dbbebad31c" }
some_num = { type = "u64", value = "42" }
some_string = { type = "str[4]", value = "\"fuel\"" }
true_bool = { type = "bool", value = "true" }

Notice that each constant requires two fields: a type and a value.

Note Because configuration-time constants are constants, they are immutable and cannot be made otherwise.

The constants defined above can now be used in a Sway program that uses the manifest file as follows:

script;

struct S {
    x: u64,
}

fn main() -> u64 {
    let addr = some_contract_addr;

    let string = some_string;

    return if true_bool { some_num } else { 0 };
}

Note Currently, it is only possible to define configuration-time constants that have primitive types and that are initialized using literals. This will change in the future.