Local Variables and Scope
Local Variables and Scope
Local variables in Move are lexically (statically) scoped. New variables are introduced with the keyword let
, which will shadow any previous local with the same name. Locals are mutable and can be updated both directly and via a mutable reference.
Declaring Local Variables
let
bindings
let
bindingsMove programs use let
to bind variable names to values:
let
can also be used without binding a value to the local.
The local can then be assigned a value later.
This can be very helpful when trying to extract a value from a loop when a default value cannot be provided.
Variables must be assigned before use
Move's type system prevents a local variable from being used before it has been assigned.
Valid variable names
Variable names can contain underscores _
, letters a
to z
, letters A
to Z
, and digits 0
to 9
. Variable names must start with either an underscore _
or a letter a
through z
. They cannot start with uppercase letters.
Type annotations
The type of local variable can almost always be inferred by Move's type system. However, Move allows explicit type annotations that can be useful for readability, clarity, or debuggability. The syntax for adding a type annotation is:
Some examples of explicit type annotations:
Note that the type annotations must always be to the right of the pattern:
When annotations are necessary
In some cases, a local type annotation is required if the type system cannot infer the type. This commonly occurs when the type argument for a generic type cannot be inferred. For example:
In a rarer case, the type system might not be able to infer a type for divergent code (where all the following code is unreachable). Both return
and abort
are expressions and can have any type. A loop
has type ()
if it has a break
, but if there is no break out of the loop
, it could have any type. If these types cannot be inferred, a type annotation is required. For example, this code:
Adding type annotations to this code will expose other errors about dead code or unused local variables, but the example is still helpful for understanding this problem.
Multiple declarations with tuples
let
can introduce more than one local at a time using tuples. The locals declared inside the parenthesis are initialized to the corresponding values from the tuple.
The type of the expression must match the arity of the tuple pattern exactly.
You cannot declare more than one local with the same name in a single let
.
Multiple declarations with structs
let
can also introduce more than one local at a time when destructuring (or matching against) a struct. In this form, the let
creates a set of local variables that are initialized to the values of the fields from a struct. The syntax looks like this:
Here is a more complicated example:
Fields of structs can serve double duty, identifying the field to bind and the name of the variable. This is sometimes referred to as punning.
is equivalent to:
As shown with tuples, you cannot declare more than one local with the same name in a single let
.
Destructuring against references
In the examples above for structs, the bound value in the let was moved, destroying the struct value and binding its fields.
In this scenario the struct value T { f1: 1, f2: 2 }
no longer exists after the let
.
If you wish instead to not move and destroy the struct value, you can borrow each of its fields. For example:
And similarly with mutable references:
This behavior can also work with nested structs.
Ignoring Values
In let
bindings, it is often helpful to ignore some values. Local variables that start with _
will be ignored and not introduce a new variable
This can be necessary at times as the compiler will error on unused local variables
General let
grammar
let
grammarAll the different structures in let
can be combined! With that we arrive at this general grammar for let
statements:
let-binding → let pattern-or-list type-annotationopt initializeropt
pattern-or-list → pattern | ( pattern-list )
pattern-list → pattern ,opt | pattern , pattern-list
type-annotation → : type
initializer → = expression
The general term for the item that introduces the bindings is a pattern. The pattern serves to both destructure data (possibly recursively) and introduce the bindings. The pattern grammar is as follows:
pattern → local-variable | struct-type { field-binding-list }
field-binding-list → field-binding ,opt | field-binding , field-binding-list
field-binding → field | field : pattern
A few concrete examples with this grammar applied:
Mutations
Assignments
After the local is introduced (either by let
or as a function parameter), the local can be modified via an assignment:
Unlike let
bindings, assignments are expressions. In some languages, assignments return the value that was assigned, but in Move, the type of any assignment is always ()
.
Practically, assignments being expressions means that they can be used without adding a new expression block with braces ({
...}
).
The assignment uses the same pattern syntax scheme as let
bindings:
Note that a local variable can only have one type, so the type of the local cannot change between assignments.
Mutating through a reference
In addition to directly modifying a local with assignment, a local can be modified via a mutable reference &mut
.
This is particularly useful if either:
(1) You want to modify different variables depending on some condition.
(2) You want another function to modify your local value.
This sort of modification is how you modify structs and vectors!
For more details, see Move references.
Scopes
Any local declared with let
is available for any subsequent expression, within that scope. Scopes are declared with expression blocks, {
...}
.
Locals cannot be used outside the declared scope.
But, locals from an outer scope can be used in a nested scope.
Locals can be mutated in any scope where they are accessible. That mutation survives with the local, regardless of the scope that performed the mutation.
Expression Blocks
An expression block is a series of statements separated by semicolons (;
). The resulting value of an expression block is the value of the last expression in the block.
In this example, the result of the block is x + y
.
A statement can be either a let
declaration or an expression. Remember that assignments (x = e
) are expressions of type ()
.
Function calls are another common expression of type ()
. Function calls that modify data are commonly used as statements.
This is not just limited to ()
types---any expression can be used as a statement in a sequence!
But! If the expression contains a resource (a value without the drop
ability), you will get an error. This is because Move's type system guarantees that any value that is dropped has the drop
ability. (Ownership must be transferred or the value must be explicitly destroyed within its declaring module.)
An expression block is itself an expression and can be used anyplace an expression is used. (Note: The body of a function is also an expression block, but the function body cannot be replaced by another expression.)
(The type annotation is not needed in this example and only added for clarity.)
Shadowing
If a let
introduces a local variable with a name already in scope, that previous variable can no longer be accessed for the rest of this scope. This is called shadowing.
When a local is shadowed, it does not need to retain the same type as before.
After a local is shadowed, the value stored in the local still exists, but will no longer be accessible. This is important to keep in mind with values of types without the drop
ability, as ownership of the value must be transferred by the end of the function.
When a local is shadowed inside a scope, the shadowing only remains for that scope. The shadowing is gone once that scope ends.
Remember, locals can change type when they are shadowed.
Move and Copy
All local variables in Move can be used in two ways, either by move
or copy
. If one or the other is not specified, the Move compiler is able to infer whether a copy
or a move
should be used. This means that in all the examples above, a move
or a copy
would be inserted by the compiler. A local variable cannot be used without the use of move
or copy
.
copy
will likely feel the most familiar coming from other programming languages, as it creates a new copy of the value inside the variable to use in that expression. With copy
, the local variable can be used more than once.
Any value with the copy
ability can be copied in this way.
move
takes the value out of the local variable without copying the data. After a move
occurs, the local variable is unavailable.
Safety
Move's type system will prevent a value from being used after it is moved. This is the same safety check described in let
declaration that prevents local variables from being used before it is assigned a value.
Inference
As mentioned above, the Move compiler will infer a copy
or move
if one is not indicated. The algorithm for doing so is quite simple:
Any value with the
copy
ability is given acopy
.Any reference (both mutable
&mut
and immutable&
) is given acopy
.Except under special circumstances where it is made a
move
for predictable borrow checker errors.
Any other value is given a
move
.If the compiler can prove that the source value with copy ability is not used after the assignment, then a move may be used instead of a copy for performance, but this will be invisible to the programmer (except in possible decreased time or gas cost).
For example:
Last updated