Go Arrays

Arrays are a type of composite data type in Golang that allows you to store a fixed-size sequence of elements of the same type. The size of an array is defined at the time of its creation and cannot be changed during the lifetime of the array.

Here is an example of how to declare and initialize an array in Golang:

package main

import "fmt"

func main() {
    var arr [5]int // Declare an array of 5 integers
    arr[0] = 1     // Set the first element to 1
    arr[1] = 2     // Set the second element to 2
    arr[2] = 3     // Set the third element to 3
    arr[3] = 4     // Set the fourth element to 4
    arr[4] = 5     // Set the fifth element to 5

    fmt.Println(arr) // Print the array to the console
}

In this example, we declare an array called arr that can hold 5 integers. We then set the values of each element in the array using their indices (remember that arrays in Golang are zero-indexed). Finally, we print the entire array to the console using the fmt.Println function.

You can also declare and initialize an array in a single line, like this:

package main

import "fmt"

func main() {
    arr := [5]int{1, 2, 3, 4, 5} // Declare and initialize an array of 5 integers

    fmt.Println(arr) // Print the array to the console
}

In this example, we declare and initialize an array called arr in a single line using curly braces {} to define the elements of the array. The size of the array is also defined within the square brackets [].

You can access the elements of an array using their indices, like this:

package main

import "fmt"

func main() {
    arr := [5]int{1, 2, 3, 4, 5} // Declare and initialize an array of 5 integers

    fmt.Println(arr[0]) // Print the first element of the array to the console
    fmt.Println(arr[1]) // Print the second element of the array to the console
    fmt.Println(arr[2]) // Print the third element of the array to the console
    fmt.Println(arr[3]) // Print the fourth element of the array to the console
    fmt.Println(arr[4]) // Print the fifth element of the array to the console
}

In this example, we access each element of the arr array using their indices and print them to the console.

Arrays are a powerful data type in Golang that can be used to store and manipulate large amounts of data. By understanding how to declare, initialize, and access arrays in Golang, you can write more efficient and effective code.

Follow us on social media
Follow Author