Icon HelpCircleForumIcon Link

⌘K

Icon HelpCircleForumIcon Link
Variables

Icon LinkVariables

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.

Icon LinkDeclaring 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.

Icon LinkType 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] = __to_str_array("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.