Golang Tutorial

Fundamentals

Control Statements

Functions & Methods

Structure

Arrays & Slices

String

Pointers

Interfaces

Concurrency

Arrays in Golang

Arrays are fundamental in most programming languages, and Go is no exception. Let's dive into arrays in Go.

Introduction

In Go, an array is a fixed-size collection of elements of the same type. The size of the array is part of its type, which means once you've defined an array of a certain size, you can't change its size.

1. Declaring and Initializing Arrays

1.1 Basic Declaration

You can declare an array by specifying its size and element type:

var arr [5]int

This declares an array of 5 integers.

1.2 Initialization

You can initialize an array at the time of declaration:

var arr [5]int = [5]int{1, 2, 3, 4, 5}

Or more simply:

arr := [5]int{1, 2, 3, 4, 5}

If you don't provide all the elements, the rest will have the zero value for the type:

arr := [5]int{1, 2, 3} // {1, 2, 3, 0, 0}

1.3 Using ellipsis (...) for size

You can let Go determine the size of the array:

arr := [...]int{1, 2, 3, 4, 5}
fmt.Println(len(arr))  // Outputs: 5

2. Accessing Array Elements

Array elements can be accessed using indices:

arr := [5]int{1, 2, 3, 4, 5}
fmt.Println(arr[2])  // Outputs: 3

arr[2] = 99
fmt.Println(arr[2])  // Outputs: 99

3. Iterating Over an Array

You can use the for loop to iterate over the array:

arr := [5]int{1, 2, 3, 4, 5}
for i, v := range arr {
    fmt.Printf("Index: %d, Value: %d\n", i, v)
}

4. Multidimensional Arrays

Go supports multi-dimensional arrays:

var matrix [3][3]int // 3x3 matrix

matrix[0] = [3]int{1, 2, 3}
matrix[1] = [3]int{4, 5, 6}
matrix[2] = [3]int{7, 8, 9}

5. Limitations and Use Cases of Arrays

  • Fixed Size: The size of an array is part of its type. This makes arrays somewhat rigid to use.
  • Value Semantics: Arrays in Go are value types. This means if you assign one array to another, a complete copy is made.

Because of the fixed-size nature of arrays, they are less frequently used in Go compared to slices, which are more flexible and dynamic.

Conclusion

Arrays form the foundational building block upon which slices (a more flexible, dynamic, and commonly-used data structure) are built. While you might find yourself using slices more often due to their dynamic nature, it's essential to understand arrays as they underpin many aspects of how Go manages data in collections.

  1. Golang Array Declaration and Initialization:

    • Arrays in Go have a fixed size and must be declared with a specific size during initialization.
    • Example:
      package main
      
      import "fmt"
      
      func main() {
          var numbers [5]int                 // Declaration with zero values
          names := [3]string{"Alice", "Bob", "Charlie"}  // Declaration and initialization
          fmt.Println(numbers)               // Output: [0 0 0 0 0]
          fmt.Println(names)                 // Output: [Alice Bob Charlie]
      }
      
  2. How to Iterate Through Arrays in Golang:

    • Use a for loop to iterate through the elements of an array.
    • Example:
      package main
      
      import "fmt"
      
      func main() {
          numbers := [5]int{1, 2, 3, 4, 5}
      
          for i := 0; i < len(numbers); i++ {
              fmt.Println(numbers[i])
          }
      }
      
  3. Arrays vs Slices in Golang:

    • Arrays have a fixed size, while slices are dynamic and can change in size.
    • Example:
      package main
      
      import "fmt"
      
      func main() {
          // Array
          arr := [3]int{1, 2, 3}
      
          // Slice
          slice := []int{1, 2, 3}
      
          fmt.Println(arr, slice)
      }
      
  4. Multi-dimensional Arrays in Golang:

    • Arrays can be multi-dimensional in Go.
    • Example:
      package main
      
      import "fmt"
      
      func main() {
          matrix := [2][3]int{
              {1, 2, 3},
              {4, 5, 6},
          }
      
          fmt.Println(matrix)
      }
      
  5. Dynamic Arrays in Golang:

    • Arrays in Go have a fixed size, and to have dynamic behavior, slices are commonly used.
    • Example:
      package main
      
      import "fmt"
      
      func main() {
          // Using slices for dynamic behavior
          dynamicArray := []int{1, 2, 3}
          dynamicArray = append(dynamicArray, 4)
          fmt.Println(dynamicArray)  // Output: [1 2 3 4]
      }
      
  6. Array Length and Capacity in Golang:

    • The length of an array is fixed at declaration, and the capacity is the maximum size it can have without resizing.
    • Example:
      package main
      
      import "fmt"
      
      func main() {
          numbers := [5]int{1, 2, 3, 4, 5}
          fmt.Println("Length:", len(numbers))
          fmt.Println("Capacity:", cap(numbers))
      }
      
  7. Copying Arrays in Golang:

    • Use the copy function to copy elements from one array to another.
    • Example:
      package main
      
      import "fmt"
      
      func main() {
          source := [3]int{1, 2, 3}
          destination := [3]int{}
      
          copy(destination[:], source[:])
      
          fmt.Println(destination)  // Output: [1 2 3]
      }
      
  8. Golang Array Indexing and Accessing Elements:

    • Access elements of an array using their index.
    • Example:
      package main
      
      import "fmt"
      
      func main() {
          numbers := [5]int{10, 20, 30, 40, 50}
          fmt.Println(numbers[2])  // Output: 30
      }
      
  9. Sorting Arrays in Golang:

    • Use the sort package to sort arrays in Go.
    • Example:
      package main
      
      import (
          "fmt"
          "sort"
      )
      
      func main() {
          numbers := [5]int{5, 2, 8, 1, 6}
          sort.Ints(numbers[:])
          fmt.Println(numbers)  // Output: [1 2 5 6 8]
      }