Uses and Aliases
The use
syntax can be used to create aliases to members in other modules. use
can be used to create aliases that last either for the entire module, or for a given expression block scope.
#
SyntaxThere are several different syntax cases for use
. Starting with the most simple, we have the following for creating aliases to other modules
For example
use 0x1::Vector;
introduces an alias Vector
for 0x1::Vector
. This means that anywhere you would want to use the module name 0x1::Vector
(assuming this use
is in scope), you could use Vector
instead. use 0x1::Vector;
is equivalent to use 0x1::Vector as Vector;
Similarly use 0x1::Vector as V;
would let you use V
instead of 0x1::Vector
If you want to import a specific module member (such as a function, struct, or constant). You can use the following syntax.
For example
This would let you use the function 0x1::Vector::empty
without full qualification. Instead you could use empty
and empty_vec
respectively. Again, use 0x1::Vector::empty;
is equivalent to use 0x1::Vector::empty as empty;
If you want to add aliases for multiple module members at once, you can do so with the following syntax
For example
If you need to add an alias to the Module itself in addition to module members, you can do that in a single use
using Self
. Self
is a member of sorts that refers to the module.
For clarity, all of the following are equivalent:
If needed, you can have as many aliases for any item as you like
module
#
Inside a Inside of a module
all use
declarations are usable regardless of the order of declaration.
The aliases declared by use
in the module usable within that module.
Additionally, the aliases introduced cannot conflict with other module members. See Uniqueness for more details
#
Inside an expressionYou can add use
declarations to the beginning of any expression block
As with let
, the aliases introduced by use
in an expression block are removed at the end of that block.
Attempting to use the alias after the block ends will result in an error
Any use
must be the first item in the block. If the use
comes after any expression or let
, it will result in a parsing error
#
Naming rulesAliases must follow the same rules as other module members. This means that aliases to structs or constants must start with A
to Z
#
UniquenessInside a given scope, all aliases introduced by use
declarations must be unique.
For a module, this means aliases introduced by use
cannot overla
And, they cannot overlap with any of the module's other members
Inside of an expression block, they cannot overlap with each other, but they can shadow other aliases or names from an outer scope
#
Shadowinguse
aliases inside of an expression block can shadow names (module members or aliases) from the outer scope. As with shadowing of locals, the shadowing ends at the end of the expression block;
#
Unused Use or AliasAn unused use
will result in an error