Go by Example: Arrays

An array is a fixed-length sequence of values of the same type.

Here’s an example of how to declare and use an array in Go:

package main

import "fmt"

func main() {
    var a [3]int
    a[0] = 1
    a[1] = 2
    a[2] = 3
    fmt.Println(a)

    b := [3]int{1, 2, 3}
    fmt.Println(b)
}

Output:

[1 2 3]
[1 2 3]

You can also use the ... syntax to let Go determine the length of the array based on the initial values:

c := [...]int{1, 2, 3}
fmt.Println(c)

An array is a fixed-length sequence of values of the same type.

Here’s an example of how to declare and use an array in Go:

cssCopy codepackage main

import "fmt"

func main() {
    var a [3]int
    a[0] = 1
    a[1] = 2
    a[2] = 3
    fmt.Println(a)

    b := [3]int{1, 2, 3}
    fmt.Println(b)
}

Output:

csharpCopy code[1 2 3]
[1 2 3]

You can also use the ... syntax to let Go determine the length of the array based on the initial values:

goCopy codec := [...]int{1, 2, 3}
fmt.Println(c)

Output:

[1 2 3]

Note that arrays are passed by value, not by reference, so changes to an array within a function will not persist outside of it. To modify an array within a function, you can pass a pointer to the array.

You can also iterate over an array using a for loop:

d := [...]int{1, 2, 3}

for i := 0; i < len(d); i++ {
    fmt.Println(d[i])
}

Output:

1
2
3

Or using the range keyword:

e := [...]int{1, 2, 3}

for i, v := range e {
    fmt.Println(i, v)
}

Output:

0 1
1 2
2 3

Arrays have a fixed length and cannot be resized, but you can create a slice, which is a dynamically-sized array, by using the make function:

f := make([]int, 3, 5)
f[0] = 1
f[1] = 2
f[2] = 3
f = append(f, 4)
fmt.Println(f)

Output:

[1 2 3 4]

Slices are more flexible than arrays and are the preferred data structure for many use cases in Go.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *