Like many other modern languages, V has built-in support for arrays. An array is a collection of elements of the same type. Array literals are lists of expressions surrounded by square brackets.
An individual element can be retrieved using an index expression.
Indexes start at
Arrays in V can only contain elements of the same type.
This means that code like
[1, 'a'] will not compile:
The type of array is determined by the first element:
[1, 2, 3]is an array of ints (
['a', 'b']is an array of strings (
The user can explicitly specify the type for the first element:
[u8(16), 32, 64, 128].
The above syntax is fine for a small number of known elements, but for very large or empty arrays there is a second initialization syntax:
This creates an array of 10000
int elements that are all initialized with
Memory space is reserved for 30000 elements.
init are optional;
len defaults to
init to the
of the element type.
The run time system makes sure that the capacity is not smaller than
(even if a smaller value is specified explicitly):
Setting the capacity improves the performance of pushing elements to the array as reallocations can be avoided:
The above code uses a range
You can initialize the array by accessing the
index variable which gives
the index as shown here:
Array with initial length
You can create an array with a specific length using the
len: length – the number of pre-allocated and initialized elements in the array.
Array with initial capacity
You can create an array with a specific capacity using the
cap: capacity – the amount of memory space which has been reserved for elements,
but not initialized or counted as elements.
The array can grow up to this size without being reallocated.
Usually, V takes care of this field automatically, but there are cases where the user
may want to do manual optimizations (see below).
Array with initial length and capacity
You can use both
cap fields to create an array with a specific length and capacity:
Array element fetching
You can fetch an element from an array using the index operator
If the index is out of bounds of the array, then a panic will be triggered and the program will end with an error:
To return the default value if the array is out of bounds, use the
or block, as in the case of
handling Result/Option types,
can contain several statements:
Append to an array
An element can be appended to the end of an array using the push operator
You can also add all the elements of another array using it:
Check if an array contains a value
To check if an array contains a specific value, you can use the
To check the opposite, use
Complexity of the
!inoperation for arrays is
O(n), where n is the length of the array.
Arrays can have more than one dimension.
2d array example:
3d array example:
All arrays can be easily printed with
println(arr) and converted to a string
s := arr.str().
Copying the data from the array is done with
Arrays can be efficiently filtered and mapped with the
it is a special variable which refers to the element currently being
processed in filter/map methods.
.all() can be used to conveniently test
for elements that satisfy a condition.
There are further built-in methods for arrays:
a.repeat(n)concatenates the array elements
a.insert(i, val)inserts a new element
iand shifts all following elements to the right
a.insert(i, [3, 4, 5])inserts several elements
a.prepend(val)inserts a value at the beginning, equivalent to
a.prepend(arr)inserts elements of array
arrat the beginning
a.trim(new_len)truncates the length (if
new_length < a.len, otherwise does nothing)
a.clear()empties the array without changing
sizeconsecutive elements from index
start– triggers reallocation
a.delete_last()removes the last element
a[a.len - 1]
a.pop()removes the last element and returns it
a.reverse()makes a new array with the elements of
ain reverse order
a.reverse_in_place()reverses the order of elements in
a.join(joiner)concatenates an array of strings into one string using
joinerstring as a separator
Array method chaining
You can chain the calls of array methods like
.map() and use the
it built-in variable
to achieve a classic
map/filter functional paradigm:
Sorting arrays of all kinds is elementary and intuitive.
b are used when providing a custom sorting condition.
Through the variables
b, you can also access the fields of structures:
V also supports custom sorting, through the
sort_with_compare array method.
Which expects a comparing function which will define the sort order.
Useful for sorting on multiple fields at the same time by custom sorting rules.
The code below sorts the array ascending on
name and descending
A slice is a part of a parent array.
Initially it refers to the elements between two indices separated by a
The right-side index must be greater than or equal to the left-side index.
If a right-side index is absent, it is assumed to be the array length. If a left-side index is absent, it is assumed to be 0.
In V slices are arrays themselves (they are not distinct types). As a result, all array operations may be performed on them. E.g. they can be pushed onto an array of the same type:
A slice is always created with the smallest possible capacity
cap == len (see
cap above) no matter what the capacity or length
of the parent array is.
As a result, it is immediately reallocated and copied to another memory location when the size increases, thus becoming independent of the parent array (copy on grow). In particular, pushing elements to a slice does not alter the parent:
Appending the parent array may or may not make it independent of its child slices. The behaviour depends on the parent's capacity and is predictable:
You can call
.clone() on the slice, if you do want to have an independent copy right away:
Slices with negative indexes
V supports array and string slices with negative indexes.
Negative indexing starts from the end of the array towards the start,
-3 is equal to
array.len - 3.
Negative slices have a different syntax from normal slices, i.e. you need
to add a
gate between the array name and the square bracket:
gate specifies that this is a different type of slice and remember that
the result is "locked" inside the array.
The returned slice is always a valid array, though it may be empty:
Fixed size arrays
V also supports arrays with fixed size. Unlike ordinary arrays, their length is constant. You cannot append elements to them, nor shrink them. You can only modify their elements in place.
However, access to the elements of fixed size arrays is more efficient, they need less memory than ordinary arrays, and unlike ordinary arrays, their data are on the stack, so you may want to use them as buffers if you do not want additional heap allocations.
Most methods are defined to work on ordinary arrays, not on fixed size arrays. You can convert a fixed size array to an ordinary array with slicing:
Note that slicing will cause the data of the fixed size array to be copied to the newly created ordinary array.