Arrays and Slices
Arrays
An array is a sequence of elements of the same type with a fixed length. The length is part of the type:
var nilai [3]int // [0 0 0]
hari := [7]string{"Sen", "Sel", "Rab", "Kam", "Jum", "Sab", "Min"}
fmt.Println(hari[0], len(hari)) // Sen 7
[3]int and [4]int are different types. Because their length is so rigid, arrays are rarely used directly in everyday Go code.
Slices
A slice is a flexible "window" onto an array behind it. Its type is written without a number: []int, []string.
menu := []string{"Espreso", "Latte", "Teh Tarik"}
fmt.Println(menu[1]) // Latte
fmt.Println(len(menu)) // 3
menu[2] = "Matcha" // elemen bisa diubah
As the last comment says, elements can be changed. A slice that hasn't been filled is nil with a length of 0. Accessing an index outside 0..len-1 causes a panic (index out of range).
Almost all Go code uses slices, not arrays.
range over a slice
range gives you the index and a copy of the value of each element:
for i, m := range menu {
fmt.Println(i, m)
}
Use _ if you don't need one of them: for _, m := range menu.
Task
A coffee shop records the cups sold each day for a week in an array [7]int (index 0 = Monday). Complete:
func totalMingguan(penjualan [7]int) int: the sum of all sales.func hariTerlaris(penjualan [7]int) int: the index of the day with the highest sales. If there's a tie, take the smallest index.func hitungDiAtas(penjualan []int, batas int) int: how many elements in the slicepenjualanare greater thanbatas(the threshold).
Use for ... range.