Search…
Arrays
An array is a collection of items stored in contiguous memory locations. It's an aggregate data structure that is designed to store a group of objects of the same type. It's the most efficient data structure for storing and accessing a sequence of objects.

How to declare an array

Create an array that holds integer values:
1
mut ages := [18, 25, 37]
2
3
println(ages)
Copied!
Output
1
[18, 25, 37]
Copied!
Or create an array that holds string values:
1
mut users := ['vbrazo', 'donnisnoni95', 'Delta456']
2
3
println(users)
Copied!
Output
1
['vbrazo', 'donnisnoni95', 'Delta456']
Copied!
Note: All elements must have the same type. The following code will not compile.
1
mut users := ['vbrazo', 'donnisnoni95', 'Delta456', 0]
Copied!
Output
1
~/main.v:2:43: bad array element type `int` instead of `string`
Copied!

Create an empty array

If you want to create a new empty array, just declare [] followed by the data type.
1
mut names := []string
2
mut numbers := []int
Copied!

Accessing element of the array

1
mut users := ['vbrazo', 'donnisnoni95', 'Delta456']
2
3
println(users[0])
4
println(users[2])
5
println(users[1])
Copied!
Output
1
vbrazo
2
Delta456
3
donnisnoni95
Copied!

Append a value to an array

<< is an operator that appends a value to the end of the array.
1
mut ages := [18]
2
ages << 47
3
4
println(ages)
Copied!
Output
1
[18, 47]
Copied!
It can also append an entire array.
1
mut ages := [18]
2
ages << [47, 49]
3
4
println(ages)
Copied!
Output
1
[18, 47, 49]
Copied!

Length/size of an array

.len method returns the length of the array.
1
mut names := ['Thiago', 'John']
2
3
println(names.len)
Copied!
Output
1
2
Copied!

In operator

in check if an element is inside an array.
1
mut names := ['Thiago', 'Alex', 'Joe']
2
3
println('Vitor' in names)
4
println('Thiago' in names)
Copied!
Output
1
false
2
true
Copied!

Slicing an array

It's easy to slice an array in V. You can slice an array with the default V slicing feature without having to call the slice () method. The syntax is like this my_array[start..end]
1
animals := ['lion', 'goose', 'chicken', 'turkey', 'tiger']
2
poultry := animals[1..4]
3
println(poultry) // ["goose", "chicken", "turkey"]
Copied!
If you want to slice from the start of the index, just ignore it to put 0 and using instead my_array[..end] or my_array[start..].
1
x := ['h', 'e', 'l', 'l', 'o']
2
y := x[..x.len-1]
3
z := x[1..]
4
println(y) // ['h', 'e', 'l', 'l']
5
println(z) // ['e', 'l', 'l', '0']
Copied!

Exercises

  1. 1.
    Write a V program to store elements in an array and print it.
  2. 2.
    Write a V program to read n number of values in an array and display it in reverse order.
  3. 3.
    Write a V program to find the sum of all elements of the array.
  4. 4.
    Write a V program to copy the elements of one array into another array.
  5. 5.
    Write a V program to count a total number of duplicate elements in an array.
Last modified 2yr ago