Vectors & Option

Function-call style (vector::push_back(&mut v, 10)) works everywhere and is what you will see in older code.

9.1 Creating and using vectors

Function-call style (vector::push_back(&mut v, 10)) works everywhere and is what you will see in older code.

let mut v: vector<u64> = vector[];       // Sui needs `let mut` to mutate
v.push_back(10);
v.push_back(20);
v.push_back(30);

let len = v.length();                    // 3
let first = v[0];                        // index syntax (Move 2024 / Move 2); copies u64
let r: &u64 = &v[1];                     // borrow
*&mut v[2] = 99;                         // mutate in place
let last = v.pop_back();                 // 99
let has = v.contains(&10);               // true
let (found, idx) = v.index_of(&20);      // (true, 1)
v.swap(0, 1);
v.reverse();
let removed = v.remove(0);               // O(n), keeps order
let swapped = v.swap_remove(0);          // O(1), changes order
assert!(v.is_empty());
v.destroy_empty();

9.2 Vectors of resources

A vector<T> has the same abilities as T (e.g., vector<Coin<SUI>> has neither copy nor drop). You must empty and destroy_empty a vector of resources, or store it.

9.3 Common vector operations

vector[], vector::empty<T>(), vector::singleton(x) push_back, insert(x, i), append(other)

pop_back, remove(i), swap_remove(i) abort if out of range v[i], borrow(i), borrow_mut(i)

length, is_empty, contains, index_of swap, reverse aborts if not empty Higher-order (Sui macros)

do!, do_ref!, do_mut!, map!, map_ref!, filter!, fold!, any!, all!, tabulate! Higher-order (Aptos)

for_each, for_each_ref, map, filter, fold, any, all inline functions with lambdas

9.4 Option

std::option::Option<T> represents an optional value (internally a vector of length 0 or 1; with Move 2024/Move 2 enums it behaves the same way from the user's perspective).

use std::option::{Self, Option};   // implicit in Sui 2024

let mut maybe: Option<u64> = option::none();
assert!(maybe.is_none());
maybe.fill(5);
assert!(maybe.is_some());
let v = *maybe.borrow();               // 5
let x = maybe.extract();               // takes the value, leaves none
let y = option::some(7).destroy_some();
let z = option::none<u64>().get_with_default(0);