Rabi Siddique
344 words
2 minutes
Arrays and Slices in Golang
2023-01-06

In Go, arrays and slices are fundamental data structures used to store collections of elements. Here’s a detailed explanation with examples.

Declaring and Initializing Arrays#

To declare an array of a fixed size, you specify the size and the element type. You can initialize the array with values at the time of declaration.

package main

import "fmt"

func arrays() {
    // Declare an array of 5 integers
    var nums [5]int
    // Initialize the array with some values
    nums = [5]int{1, 3, 4, 4, 5}
    fmt.Println(nums)
}

Using Slices and the append Function#

Slices in Go are more flexible than arrays. You can create a slice from an array and dynamically change its size using the append function.

func arrays() {
    // Create a slice and initialize it with values
    a := []int{1, 2, 3}
    // Append a value to the slice
    a = append(a, 4)
    fmt.Println(a) // Output: [1 2 3 4]
}

Short Variable Declaration for Arrays#

You can use the short variable declaration syntax to create and initialize arrays.

func arrays() {
    // Declare and initialize an array using short variable declaration
    b := [5]int{1, 2, 3, 4, 5}
    fmt.Println(b) // Output: [1 2 3 4 5]
}

Omitting Length in Slices#

When working with slices, you can omit the length if the initializer provides enough values.

func arrays() {
    // Create a slice without specifying the length
    c := []int{1, 2, 3, 4, 5, 6}
    fmt.Println(c) // Output: [1 2 3 4 5 6]
}

Iterating Over Arrays and Slices#

You can use a for loop to iterate over the elements of an array or slice.

func arrays() {
    c := []int{1, 2, 3, 4, 5, 6}
    // Iterate using a traditional for loop
    for i := 0; i < len(c); i++ {
        fmt.Println(c[i])
    }
}

Alternatively, you can use the range form of the for loop, which provides both the index and the value of each element.


func arrays() {
    c := []int{1, 2, 3, 4, 5, 6}
    // Iterate using a range for loop
    for i, v := range c {
        fmt.Println("Index:", i, "Value:", v)
    }
}

func main() {
    arrays()
}

Arrays and Slices in Golang
https://rabisiddique.com/posts/arrays-slices-in-golang/
Author
Rabi Siddique
Published at
2023-01-06