Skip to main content
Version: v0.30.0

Vectors

caution

This feature is experimental. You should expect it to change in future versions, cause unexpected behavior, or simply not work at all.

A vector is a collection type similar to Rust's Vec<T> type. In Noir, it is a convenient way to use slices as mutable arrays.

Example:

let mut vector: Vec<Field> = Vec::new();
for i in 0..5 {
vector.push(i);
}
assert(vector.len() == 5);

Methods

new

Creates a new, empty vector.

pub fn new() -> Self

Example:

let empty_vector: Vec<Field> = Vec::new();
assert(empty_vector.len() == 0);

from_slice

Creates a vector containing each element from a given slice. Mutations to the resulting vector will not affect the original slice.

pub fn from_slice(slice: [T]) -> Self

Example:

let slice: [Field] = &[1, 2, 3];
let vector_from_slice = Vec::from_slice(slice);
assert(vector_from_slice.len() == 3);

len

Returns the number of elements in the vector.

pub fn len(self) -> Field

Example:

let empty_vector: Vec<Field> = Vec::new();
assert(empty_vector.len() == 0);

get

Retrieves an element from the vector at a given index. Panics if the index points beyond the vector's end.

pub fn get(self, index: Field) -> T

Example:

let vector: Vec<Field> = Vec::from_slice(&[10, 20, 30]);
assert(vector.get(1) == 20);

push

Adds a new element to the vector's end, returning a new vector with a length one greater than the original unmodified vector.

pub fn push(&mut self, elem: T)

Example:

let mut vector: Vec<Field> = Vec::new();
vector.push(10);
assert(vector.len() == 1);

pop

Removes an element from the vector's end, returning a new vector with a length one less than the original vector, along with the removed element. Panics if the vector's length is zero.

pub fn pop(&mut self) -> T

Example:

let mut vector = Vec::from_slice(&[10, 20]);
let popped_elem = vector.pop();
assert(popped_elem == 20);
assert(vector.len() == 1);

insert

Inserts an element at a specified index, shifting subsequent elements to the right.

pub fn insert(&mut self, index: Field, elem: T)

Example:

let mut vector = Vec::from_slice(&[10, 30]);
vector.insert(1, 20);
assert(vector.get(1) == 20);

remove

Removes an element at a specified index, shifting subsequent elements to the left, and returns the removed element.

pub fn remove(&mut self, index: Field) -> T

Example:

let mut vector = Vec::from_slice(&[10, 20, 30]);
let removed_elem = vector.remove(1);
assert(removed_elem == 20);
assert(vector.len() == 2);