0
0
Goprogramming~5 mins

Array initialization in Go

Choose your learning style9 modes available
Introduction
Arrays hold a fixed number of items of the same type. Initializing an array means creating it and setting its starting values.
When you know the exact number of items you want to store.
When you want to store a list of fixed size, like days in a week or months in a year.
When you want to prepare a container to hold values before filling it later.
When you want to set default values for a group of items at once.
Syntax
Go
package main

import "fmt"

type ArrayExample struct {
    items [5]int
}

func main() {
    var example ArrayExample
    example.items = [5]int{1, 2, 3, 4, 5} // Initialize array with values
    fmt.Println(example.items)
}
Arrays in Go have a fixed size defined at compile time.
You can initialize arrays with values using curly braces {}.
Examples
This creates an empty array of size 3 with default zero values.
Go
var numbers [3]int
// Creates an array of 3 integers, all set to 0 by default
Here, the array is created with 7 days of the week as initial values.
Go
var days = [7]string{"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"}
// Creates and initializes an array of 7 strings
This shows an array with just one element.
Go
var singleElement = [1]int{42}
// Array with only one element
An array with zero length is allowed but holds no elements.
Go
var emptyArray [0]int
// Array with zero length
Sample Program
This program creates an array with 5 numbers, prints it, changes the first and last values, then prints it again.
Go
package main

import "fmt"

func main() {
    // Initialize an array of 5 integers with values
    var numbers = [5]int{10, 20, 30, 40, 50}

    fmt.Println("Array before change:", numbers)

    // Change the first and last elements
    numbers[0] = 100
    numbers[4] = 500

    fmt.Println("Array after change:", numbers)
}
OutputSuccess
Important Notes
Time complexity to access or change an element is O(1) because arrays allow direct access by index.
Space complexity is fixed and depends on the array size declared.
Common mistake: Trying to add more elements than the array size causes a compile-time error.
Use arrays when the size is fixed and known. Use slices when the size can change.
Summary
Arrays hold a fixed number of items of the same type.
You create arrays by specifying size and optionally initial values.
Access and change elements by their index quickly.