Arrays and Slices in Go

Introduction to Arrays and Slices

Arrays and slices in Go are used to store multiple elements of the same type. Arrays have a fixed size, while slices provide a more flexible and dynamic way to handle collections.

Declaring an Array

An array in Go is declared using the following syntax:

package main

import "fmt"

func main() {
    var numbers [5]int  // Declaring an array of size 5
    numbers[0] = 10     // Assigning values
    numbers[1] = 20
    fmt.Println(numbers)
}

Here, we define an integer array of size 5 and assign values to some of its elements.

Initializing an Array

Arrays can be initialized with predefined values at the time of declaration.

package main

import "fmt"

func main() {
    numbers := [5]int{1, 2, 3, 4, 5}
    fmt.Println(numbers)
}

Here, the array is initialized with five values in a single line.

Working with Slices

Slices in Go provide a more flexible alternative to arrays. Unlike arrays, slices do not have a fixed size.

package main

import "fmt"

func main() {
    numbers := []int{10, 20, 30, 40}
    fmt.Println(numbers)
}

Here, we create a slice containing four integer values.

Using the make Function for Slices

The make function allows creating slices with an initial size.

package main

import "fmt"

func main() {
    numbers := make([]int, 3)
    numbers[0] = 5
    numbers[1] = 10
    numbers[2] = 15
    fmt.Println(numbers)
}

Here, a slice of size 3 is created using make and values are assigned dynamically.

Appending to a Slice

Slices can dynamically grow using the append function.

package main

import "fmt"

func main() {
    numbers := []int{1, 2, 3}
    numbers = append(numbers, 4, 5)
    fmt.Println(numbers)
}

Here, new elements are appended to the existing slice.

Slice Operations

Slices support indexing and slicing operations.

package main

import "fmt"

func main() {
    numbers := []int{10, 20, 30, 40, 50}
    fmt.Println(numbers[1:4]) // Extracting elements from index 1 to 3
}

Here, a sub-slice is created from an existing slice.

Conclusion

Arrays and slices are essential data structures in Go. While arrays provide fixed-size storage, slices offer flexibility by dynamically growing or shrinking in size.

In the next lesson, we will explore Maps in Go, a powerful data structure for key-value storage.