Arrays
Examples
Filter
package main
import "fmt"
func main() {
var a [5]int
fmt.Println("emp:", a)
a[4] = 100
fmt.Println("set:", a)
fmt.Println("get:", a[4])
fmt.Println("len:", len(a))
b := [5]int{1, 2, 3, 4, 5}
fmt.Println("dcl:", b)
var twoD [2][3]int
for i := 0; i < 2; i++ {
for j := 0; j < 3; j++ {
twoD[i][j] = i + j
}
}
fmt.Println("2d: ", twoD)
}
mut nums := [1, 2, 3]
println(nums) // "[1, 2, 3]"
println(nums[1]) // "2"
nums << 4
println(nums) // "[1, 2, 3, 4]"
nums << [5, 6, 7]
println(nums) // "[1, 2, 3, 4, 5, 6, 7]"
mut names := ['John']
names << 'Peter'
names << 'Sam'
// names << 10 <-- This will not compile. `names` is an array of strings.
println(names.len) // "3"
println('Alex' in names) // "false"
names = [] // The array is now empty
// We can also preallocate a certain amount of elements.
println('\nfunction repeat()')
println('We can also preallocate a certain amount of elements.')
ids := [0].repeat(5) // This creates an array with 50 zeros
println('ids := [0].repeat(5) // $ids\n')
nums2 := [1, 2, 3, 4, 5, 6]
// it is a special variable that refers to an element in filter/map methods.
even := nums2.filter(it % 2 == 0)
println(even) // [2, 4, 6]
words := ['hello', 'world']
upper := words.map(it.to_upper())
println(upper) // ['HELLO', 'WORLD']
// Array Functions
// array.delete(id type)
println('\nfunction delete()')
println('Deletes the element present in the array at index ix.')
mut even_numbers := [2, 4, 6, 8, 10]
even_numbers.delete(3)
println('[2, 4, 6, 8, 10].delete(3) // $even_numbers')
// array.reverse()
println('\nfunction reverse()')
println('Reverses the array.')
float_num := [1.1, 1.3, 1.25, 1.4]
float_num.reverse() // [1.4, 1.25, 1.3, 1.1]
println('float_num := [1.1, 1.3, 1.25, 1.4]')
println('float_num.reverse() // $float_num')
// array.clone()
println('\nfunction clone()')
println('Clones and returns a new array.')
c_array := [1, 2, 3, 4, 5]
c_array1 := c_array.clone()
println('c_array := [1, 2, 3, 4, 5]')
println('c_array1 := c_array.clone() // c_array1 = $c_array1')
Last Run
:
[1, 2, 3]
2
[1, 2, 3, 4]
[1, 2, 3, 4, 5, 6, 7]
3
false
function repeat()
We can also preallocate a certain amount of elements.
ids := [0].repeat(5) // [0, 0, 0, 0, 0]
[2, 4, 6]
['HELLO', 'WORLD']
function delete()
Deletes the element present in the array at index ix.
[2, 4, 6, 8, 10].delete(3) // [2, 4, 6, 10]
function reverse()
Reverses the array.
float_num := [1.1, 1.3, 1.25, 1.4]
float_num.reverse() // [1.1, 1.3, 1.25, 1.4]
function clone()
Clones and returns a new array.
c_array := [1, 2, 3, 4, 5]
c_array1 := c_array.clone() // c_array1 = [1, 2, 3, 4, 5]