CodeBlanks Logo Icon CodeBlanks

Array declaration

Learn to declare fixed-size arrays.

Defining arrays

An array is a fixed-length sequence of elements of the same type. The length is part of the type: [3]int and [4]int are different types.

var notlar [3]int        // [0 0 0]
notlar[0] = 90
gunler := [...]string{"Pzt", "Sal", "Çar"}  // length 3
fmt.Println(notlar, len(gunler))

Indexes start at 0; an out-of-range index errors at compile or run time.

When to use arrays

Arrays suit small data whose length is known exactly at compile time: an RGB color ([3]uint8), a chessboard ([8][8]Tas), a SHA-256 digest ([32]byte). Arrays can be compared with == and can be map keys. In everyday code the flexible-length slice is used most of the time.

Practice Array average

Declare notlar := [4]int{70, 85, 90, 55}. Sum it with for, compute the average as a float64 and print it.

Starter code

main.go
package main

import "fmt"

func main() {
    // buraya yaz
}

Sample solution

main.go
package main

import "fmt"

func main() {
    notlar := [4]int{70, 85, 90, 55}
    toplam := 0
    for _, n := range notlar {
        toplam += n
    }
    fmt.Println(float64(toplam) / float64(len(notlar)))
}

Expected output

75

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What happens when an array is assigned to another variable?

  • Only the first element is copied
  • A compile error
  • All elements are copied Correct answer
  • They share the same memory

Explanation: Arrays are value types; changing b after b := a doesn't affect a. Slices, by contrast, share the same array.

2 Count the length

Question
renk := [____]uint8{255, 128, 0}
Answer
renk := [...]uint8{255, 128, 0}

Explanation: [...] lets the compiler infer the length from the number of elements.

3 Expression and result

Term Meaning
var a [3]int [0 0 0]
len([5]int{}) 5
[3]int == [4]int Different types, not comparable
b := a A copy

All lessons in Beginner