Vec
.
This trait extends the read functionality with methods to append new elements
and modify existing ones.
Signature
Trait functions
get
Returns a mutable storage path to the element at the specified index, orNone
if out of
bounds.
Signature
Examples
at
Returns a mutable storage path to the element at the specified index.Panics
Panics if the index is out of bounds.Examples
Signature
len
Returns the number of elements in the vector. The length is stored at the vector’s base storage address and is automatically updated when elements are appended.Signature
Examples
append
Returns a mutable storage path to write a new element at the end of the vector. This operation:- Increments the vector’s length
- Returns a storage path to write the new element
Signature
Examples
allocate
Allocates space for a new element at the end of the vector, returning a mutable storage path to write the element. This function is a replacement for the deprecatedappend
function, which allowed
appending new elements to a vector.
Unlike push
, which gets an object to write to the vector, allocate
is specifically
useful when you need to prepare space for elements of unknown or dynamic size (e.g.,
appending another vector).
Use Case
allocate
is essential when pushing a vector into another vector, as the size of the
nested vector is unknown at compile time. It allows the caller to allocate the required
space first, then write the nested vector into the allocated space using .write()
.
This is necessary because pushing directly (e.g., vec.push(nested_vec)
) is not supported
due to Vec
being only a storage abstraction.
Deprecation Note
Theappend
function is now deprecated. Use allocate
to achieve the same functionality
with improved clarity and flexibility.
Examples
Signature
push
Pushes a new value onto the vector. This operation:- Increments the vector’s length.
- Writes the provided value to the new storage location at the end of the vector.
Note
If you need to allocate storage without writing a value (e.g., when appending another vector), consider usingallocate
instead.
Examples
Signature
pop
Pops the last value off the vector. This operation:- Retrieves the value stored at the last position in the vector.
- Decrements the vector’s length.
- Returns the retrieved value or
None
if the vector is empty.