본문 바로가기
Go

[Go] Array

by llHoYall 2021. 10. 10.

An array is a collection of values all of which have the same type.

The value that an array has is called an element.

The syntax of array definition is following:

var VARIABLE_NAME [NUMBER_OF_ELEMENTS]DATA_TYPE
var numArr [3]int
numArr[0] = 1
numArr[1] = 2
numArr[2] = 3
fmt.Println(numArr[0], numArr[1], numArr[2])
// 1 2 3

An array is static. Therefore, it is not possible to add a new element after it is declared.

The number of elements must specify with constant number.

Zero Initialization

As with variables, when creating an array, all values in the array are initialized to zero values of the type of array.

var strArr [3]string
var numArr [3]int
var boolArr [3]bool
fmt.Println(strArr[0], numArr[0], boolArr[0]
//  0 false

Array Literal

We can define an array easily using the array literal.

var strArr [3]string = [3]string{"one", "two", "three"}
fmt.Println(strArr)
// [one two three]

numArr := [3]int{1, 2, 3}
fmt.Println(numArr)
// [1 2 3]

floatArr := [5]float64{1: 3.14, 3: 2.72}
fmt.Println(floatArr)
// [0 3.14 0 2.72 0]

uint8Arr := [...]uint8{1, 3,  5 ,7}
fmt.Println(uint8Arr)
// [1 3 5 7]

Array with Loop

fruits := [3]string{"apple", "banana", "cherry"}

for i := 0; i < len(fruits); i++ {
  fmt.Println(i, fruits[i])
}
// 0 apple
// 1 banana
// 2 cherry

for index, value := range fruits {
  fmt.Println(index, value)
}
// 0 apple
// 1 banana
// 2 cherry

len() function returns the size of the array.

Array Assignment

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

fmt.Println(b)
// [1 2 3 4 5]

a[3] = 14
fmt.Println(b)
// [1 2 3 4 5]

If you assign an array to the other variable, the value is just copied to a different memory space.

Multi-Dimensional Array

arr := [2][3]int{
  {11, 12, 13},
  {21, 22, 23},
}

fmt.Println(arr)
// [[11 12 13] [21 22 23]]

for i1, a := range arr {
  fmt.Printf("Outer: %d: %d\n", i1, a)
  for i2, v := range a {
    fmt.Printf("Inner: %d: %d\n", i2, v)
  }
}
// Outer: 0: [11 12 13]
// Inner: 0: 11
// Inner: 1: 12
// Inner: 2: 13
// Outer: 1: [21 22 23]
// Inner: 0: 21
// Inner: 1: 22
// Inner: 2: 23

It is easy to make sense.

'Go' 카테고리의 다른 글

[Go] Pointer  (0) 2021.10.11
[Go] Structure  (0) 2021.10.11
[Go] Control Flow  (0) 2021.10.10
[Go] Constant  (0) 2021.10.05
[Go] The Error of Floating Point Number  (0) 2021.10.04

댓글