0
0
Goprogramming~5 mins

Array declaration in Go

Choose your learning style9 modes available
Introduction
Arrays help you store many values of the same type together, like a row of mailboxes holding letters.
When you know exactly how many items you want to store.
When you want to keep items in order and access them by position.
When you want to group related data, like daily temperatures for a week.
When you want to quickly access items using their index number.
Syntax
Go
package main

import "fmt"

func main() {
    var arrayName [size]Type
}
Replace arrayName with your variable name.
Replace size with a fixed number for how many items the array holds.
Replace Type with the type of items, like int, string, etc.
Examples
An array of 3 integers, all start as zero because Go sets default values.
Go
package main

import "fmt"

func main() {
    var emptyArray [3]int
    fmt.Println(emptyArray) // [0 0 0]
}
An array with one string element assigned.
Go
package main

import "fmt"

func main() {
    var singleElementArray [1]string
    singleElementArray[0] = "hello"
    fmt.Println(singleElementArray) // [hello]
}
An array of 4 strings initialized with values.
Go
package main

import "fmt"

func main() {
    var fruits [4]string = [4]string{"apple", "banana", "cherry", "date"}
    fmt.Println(fruits)
}
Assigning values to the first and last positions in the array.
Go
package main

import "fmt"

func main() {
    var numbers [5]int
    numbers[0] = 10
    numbers[4] = 50
    fmt.Println(numbers) // [10 0 0 0 50]
}
Sample Program
This program shows how to declare an array, see its default values, assign new values, and print the array before and after.
Go
package main

import "fmt"

func main() {
    // Declare an array of 5 integers
    var dailyTemperatures [5]int

    // Print the array before assigning values
    fmt.Println("Before assigning values:", dailyTemperatures)

    // Assign temperatures
    dailyTemperatures[0] = 70
    dailyTemperatures[1] = 72
    dailyTemperatures[2] = 68
    dailyTemperatures[3] = 65
    dailyTemperatures[4] = 74

    // Print the array after assigning values
    fmt.Println("After assigning values:", dailyTemperatures)
}
OutputSuccess
Important Notes
Time complexity to access any element by index is O(1), very fast.
Space complexity is fixed and depends on the array size you declare.
Common mistake: Trying to add more elements than the declared size causes errors.
Use arrays when size is fixed; use slices if you need flexible size.
Summary
Arrays store multiple values of the same type in a fixed size.
You declare arrays with a size and type, like [5]int for five integers.
Access array items by their position using indexes starting at 0.