Vector
vector<T>
is the only primitive collection type provided by Move. A vector<T>
is a homogenous collection of T
's that can grow or shrink by pushing/popping values off the "end".
A vector<T>
can be instantiated with any type T
. For example, vector<u64>
, vector<address>
, vector<0x42::MyModule::MyResource>
, and vector<vector<u8>>
are all valid vector types.
Literals
General vector
Literals
vector
LiteralsVectors of any type can be created with vector
literals.
In these cases, the type of the vector
is inferred, either from the element type or from the vector's usage. If the type cannot be inferred, or simply for added clarity, the type can be specified explicitly:
Example Vector Literals
vector<u8>
literals
vector<u8>
literalsA common use-case for vectors in Move is to represent "byte arrays", which are represented with vector<u8>
. These values are often used for cryptographic purposes, such as a public key or a hash result. These values are so common that specific syntax is provided to make the values more readable, as opposed to having to use vector[]
where each individual u8
value is specified in numeric form.
There are currently two supported types of vector<u8>
literals, byte strings and hex strings.
Byte Strings
Byte strings are quoted string literals prefixed by a b
, e.g. b"Hello!\n"
.
These are ASCII encoded strings that allow for escape sequences. Currently, the supported escape sequences are:
Hex Strings
Hex strings are quoted string literals prefixed by a x
, e.g. x"48656C6C6F210A"
.
Each byte pair, ranging from 00
to FF
, is interpreted as hex encoded u8
value. So each byte pair corresponds to a single entry in the resulting vector<u8>
.
Example String Literals
Operations
vector
provides several operations via the std::vector
module in the Move standard library, as shown below. More operations may be added over time. Up-to-date document on vector
can be found here.
Example
Destroying and copying vector
s
vector
sSome behaviors of vector<T>
depend on the abilities of the element type, T
. For example, vectors containing elements that do not have drop
cannot be implicitly discarded like v
in the example above--they must be explicitly destroyed with vector::destroy_empty
.
Note that vector::destroy_empty
will abort at runtime unless vec
contains zero elements:
But no error would occur for dropping a vector that contains elements with drop
:
Similarly, vectors cannot be copied unless the element type has copy
. In other words, a vector<T>
has copy
if and only if T
has copy
. However, even copyable vectors are never implicitly copied:
Copies of large vectors can be expensive, so the compiler requires explicit copy
's to make it easier to see where they are happening.
For more details see the sections on type abilities and generics.
Ownership
As mentioned above, vector
values can be copied only if the elements can be copied. In that case, the copy must be explicit via a copy
or a dereference *
.