Arrays
Overview
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 0
.
Arrays in V can only contain elements of the same type.
This means that code like [1, 'a']
will not compile:
Array Initialization
The type of array is determined by the first element:
[1, 2, 3]
is an array of ints ([]int
).['a', 'b']
is an array of strings ([]string
).
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 3
.
Memory space is reserved for 30000 elements.
The parameters len
, cap
and init
are optional;
len
defaults to 0
and init
to the
Zero-value
of the element type.
The run time system makes sure that the capacity is not smaller than len
(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
for
statement.
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
field:
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
field:
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 len
and 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:
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 in
operator:
To check the opposite, use !in
:
Complexity of the
in
and!in
operation for arrays isO(n)
, where n is the length of the array.
Multidimensional Arrays
Arrays can have more than one dimension.
2d array example:
3d array example:
Array methods
All arrays can be easily printed with println(arr)
and converted to a string
with s := arr.str()
.
Copying the data from the array is done with .clone()
:
Arrays can be efficiently filtered and mapped with the .filter()
and
.map()
methods:
.map()
:
it
variable
it
is a special variable which refers to the element currently being
processed in filter/map methods.
Additionally, .any()
and .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 elementsn
timesa.insert(i, val)
inserts a new elementval
at indexi
and shifts all following elements to the righta.insert(i, [3, 4, 5])
inserts several elementsa.prepend(val)
inserts a value at the beginning, equivalent toa.insert(0, val)
a.prepend(arr)
inserts elements of arrayarr
at the beginninga.trim(new_len)
truncates the length (ifnew_length < a.len
, otherwise does nothing)a.clear()
empties the array without changingcap
(equivalent toa.trim(0)
)a.delete_many(start, size)
removessize
consecutive elements from indexstart
– triggers reallocationa.delete(index)
equivalent toa.delete_many(index, 1)
a.delete_last()
removes the last elementa.first()
equivalent toa[0]
a.last()
equivalent toa[a.len - 1]
a.pop()
removes the last element and returns ita.reverse()
makes a new array with the elements ofa
in reverse ordera.reverse_in_place()
reverses the order of elements ina
a.join(joiner)
concatenates an array of strings into one string usingjoiner
string as a separator
See all methods of array
struct
and
vlib/arrays
module.
Array method chaining
You can chain the calls of array methods like .filter()
and .map()
and use the
it
built-in variable
to achieve a classic map/filter
functional paradigm:
Sorting arrays
Sorting arrays of all kinds is elementary and intuitive.
Special variables a
and b
are used when providing a custom sorting condition.
Through the variables a
and 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 age
.
Array slices
A slice is a part of a parent array.
Initially it refers to the elements between two indices separated by a ..
operator.
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,
for example -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: a#[..-3]
.
The 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.