Arrays in Go

Arrays

Understanding Arrays in Go Programming Language

Arrays in Go (or Golang) are conceptually similar to arrays in other programming languages. They are particularly useful when you need to manage a collection of data of the same type, such as storing a list of student scores. An array is a fixed-length data structure used to store homogeneous elements in memory. However, because arrays have a fixed size, slices are often preferred in Go.

Key Features of Arrays in Go

  • Arrays are fixed in size, meaning their length cannot change once defined.

  • Arrays allow zero or more elements of the same type.

  • Array elements are accessed using their zero-based index, with the first element at index array[0] and the last at array[len(array)-1].

  • Arrays are mutable, allowing modification of elements by their index.

Creating and Accessing Arrays in Go

Using the var Keyword

Arrays in Go can be declared using the var keyword.

Syntax:

var array_name [length]Type

Key Points

  • Arrays are mutable, so you can update their elements using the index
var array_name [length]Type
array_name[index] = value
  • Access elements using their index or iterate through the array using a loop.
  • Arrays in Go are one-dimensional by default.
  • Duplicate elements are allowed.
package main

import "fmt"

func main() {
    var numbers [5]int
    numbers[0] = 10
    numbers[1] = 20
    numbers[2] = 30
    numbers[3] = 40
    numbers[4] = 50

    fmt.Println("Array elements:")
    for i := 0; i < len(numbers); i++ {
        fmt.Println(numbers[i])
    }
}

Output:

Array elements:
10
20
30
40
50

Using Shorthand Declaration

A shorthand declaration allows you to define and initialize an array in a single line.

Syntax:

array_name := [length]Type{element1, element2, ..., elementN}

Example 2: Shorthand Declaration

package main

import "fmt"

func main() {
    colors := [3]string{"Red", "Green", "Blue"}

    fmt.Println("Colors in the array:")
    for _, color := range colors {
        fmt.Println(color)
    }
}

Output:

Array elements:
10
20
30
40
50

Using Shorthand Declaration: A shorthand declaration allows you to define and initialize an array in a single line.

Syntax:

array_name := [length]Type{element1, element2, ..., elementN}

Example 2: Shorthand Declaration

package main

import "fmt"

func main() {
    colors := [3]string{"Red", "Green", "Blue"}

    fmt.Println("Colors in the array:")
    for _, color := range colors {
        fmt.Println(color)
    }
}

Output:

Colors in the array:
Red
Green
Blue
Multi-Dimensional Arrays

In Go, arrays are one-dimensional, but you can create multi-dimensional arrays (arrays of arrays). These arrays allow you to store data in tabular or matrix format.

Syntax

var array_name [Length1][Length2]...[LengthN]Type

Example:

package main

import "fmt"

func main() {
    matrix := [2][2]int{{1, 2}, {3, 4}}

    fmt.Println("Matrix elements:")
    for i := 0; i < 2; i++ {
        for j := 0; j < 2; j++ {
            fmt.Printf("%d ", matrix[i][j])
        }
        fmt.Println()
    }
}

Output:

Matrix elements:
1 2
3 4

How to Copy an Array into Another Array in Golang?

In Go, an array is a fixed-size data structure that stores elements of the same type. Unlike slices, arrays have a predefined size that cannot be changed after declaration. Copying one array into another is straightforward but requires both arrays to have the same length and type.

Syntax:

for i := 0; i < len(sourceArray); i++ {
    targetArray[i] = sourceArray[i]
}

Example:

package main

import "fmt"

// Array used for demonstration
var sourceArray = [5]int{1, 2, 3, 4, 5}

func main() {
    fmt.Println("Original Array:", sourceArray)
}

Output:

Product of 2, 3, 4: 24
Product of 6, 7: 42
Product with no numbers: 1
1. Using a Loop to Copy an Array

Go does not have a built-in copy() function for arrays. The most common method involves manually iterating over each element of the source array and copying it to the target array.

Syntax

for i := 0; i < len(sourceArray); i++ {
    targetArray[i] = sourceArray[i]
}

Example:

package main

import "fmt"

// Predefined source array
var sourceArray = [5]int{1, 2, 3, 4, 5}

func main() {
    // Initialize target array with the same size as the source
    var targetArray [5]int

    // Copy each element manually
    for i := 0; i < len(sourceArray); i++ {
        targetArray[i] = sourceArray[i]
    }

    fmt.Println("Source Array:", sourceArray)
    fmt.Println("Target Array:", targetArray)
}

Output:

Source Array: [1 2 3 4 5]
Target Array: [1 2 3 4 5]

2. Direct Assignment (Specific to Arrays, Not Applicable to Slices)

In Go, arrays can be directly assigned to another array if their type and length are identical. This provides a simpler way to copy arrays compared to looping.

Syntax:

targetArray = sourceArray

Example:

package main

import "fmt"

// Source array for demonstration
var sourceArray = [5]int{6, 7, 8, 9, 10}

func main() {
    // Assign source array to the target array
    var targetArray [5]int = sourceArray

    fmt.Println("Source Array:", sourceArray)
    fmt.Println("Target Array:", targetArray)
}

Output:

Source Array: [6 7 8 9 10]
Target Array: [6 7 8 9 10]
3. Using Pointers for Large Arrays

When dealing with large arrays, it is more efficient to use pointers to reference the memory location of the source array instead of copying all its elements. This approach allows direct manipulation of the array data without duplicating it.

Syntax

targetPointer = &sourceArray

Example:

package main

import "fmt"

// Example source array
var sourceArray = [5]int{11, 12, 13, 14, 15}

func main() {
    // Create a pointer to the source array
    var targetPointer *[5]int = &sourceArray

    fmt.Println("Source Array:", sourceArray)
    fmt.Println("Target Array via Pointer:", *targetPointer)
}

Output:

Source Array: [11 12 13 14 15]
Target Array via Pointer: [11 12 13 14 15]