Array
A fixed size container for any element type.
Overview
An Array is a container that holds many values inside. Nara Arrays have a fixed size, you create the array with a number of elements it can hold, and then it never grows nor shrinks. Indexes are zero-based.
If you want a resizable Array use ArrayList.
Creation
Arrays have a literal syntax. Here we create a String Array of 3 elements:
var names: Array[String] = ["John", "Ahmed", "Yuto"]
To create an array with a variable size use Array::new and pass a
initial value or a generator function:
// Creating an array of 100 elements, all `0`
var numbers1 = Array::new(size: 100, init: 0)
// [0, 0, 0, 0, ...]
// Creating an array of 100 elements, but with custom elements
var numbers2 = Array::new_with_gen(size: 100, generator: #{ $0 ** 2 })
// [0, 1, 4, 9, ...]
Access elements
To access the elements of an array use square brackets:
var names = ["John", "Ahmed", "Yuto"]
print(names[2]) //: Yuto
This access panics the thread of execution when the index is invalid.
For a safe alternative use Array.get(usize), which returns the value
or null.
var names = ["John", "Ahmed", "Yuto"]
var friend = names.get(3)
friend == null
Setting elements
Use square brackets to set the value in an array. When doing this, you cannot assign to an invalid index, otherwise the thread panics. You cannot use this syntax to grow the array.
var names = ["John", "Ahmed", "Yuto"]
names[0] = "Sarah" // ok
names[3] = "Bob" //! panic, index out of bounds
Functions
fun copy(self) -> Array['E]
Creates a new array with shallow copies of all elements
fun empty(self) -> bool
Returns `true` if the array has no elements
fun new(size: u64, init: 'E) -> Array['E]
Creates a new array with `size` elements, and all values as `init`.
fun new_with_gen(size: u64, generator: fun(...) -> 'E) -> Array['E]
Creates a new array with `size` elements, and all values as `init`.
fun len(self) -> u64
Returns the size of this array
fun get(self, at: usize) -> ?'Element
Returns the element at position `at`, or `null` if the position is out of bounds
fun find(self, predicate: fun(...) -> bool) -> ?'Element
Returns the first element that satisfies `predicate`, or `null` if not found
fun foldl(self, init: 'A, reducer: fun('A, 'B) -> 'A) -> 'A
Accumulates all values of the array into a single value
fun to_lowercase(self) -> self
Clones the string as lowercase