Leon Chaewon Kong's dev blog

[TIL] Go - Array, slice, map, struct

Today I learned about array, slice, map and struct of Go.


In Go, array can be defined like:

names := [5]string{"a", "b"}

Unlike JavaScript’s array or Python’s list, the lenght of array in Go is fixed. In case above, I created array with length of 5. so, case below throws an error:

names[2] = "c"
names[3] = "d"
names[4] = "e"

// below throws an error
names[5] = "f"

Array can be traversed by using for loop and range.

simpleArray := [5]string{"a", "b", "c", "d", "e"}
for index, element := range simpleArray {
  fmt.Println(index, element)


Slices are simmilar to array, yet the length is not fixed; dynamic.

There are briefly two ways to create slices.

First, using make.

a := make([]int, 5, 10)

Code above generates a slice length of 5 and max-length of 10.

a := []int{1, 2, 30, 100}

Code above generates a slice that automatically has length of 4.

The size of a slice is dynamically determined.

by using append, new slice with appended data could be easily created.

a := []int{1, 2, 3}
b := append(a, 4)
// [1 2 3 4]

range is available just like arrays.

simpleSlice := []string{"a", "b", "c", "d"}
for index, element := range simpleSlice {
  fmt.Println(index, element)


Map offers a key / value store. Simmilar to Java’s map. Unlike JavaScript or Python, however, the map in go should only have predetermined type of key / value pairs.

For instance,

stringMap := map[string]string{"name": "Leon", "age": "29"}

stringMap should only have string key and string value.

simpleMap := map[string]int{"year": 2020, "month": 9, "day": 16}
// map[day:16 month:9 year:2020]

Maps can be iterated like arrays do:

// Map
simpleMap := map[string]string{"name": "Leon", "age": "29"}
for key, value := range simpleMap {
	fmt.Println(key, value)


A Struct can contain multiple types of values. Simmilar to maps, structs stores key / value pairs of data.

type person struct {
	name          string
	age           int
	favoriteFoods []string

favoriteFoods := []string{"Spaghetti", "bulgogi"}
leon := person{name: "Leon", age: 29, favoriteFoods: favoriteFoods}
// {Leon 29 [Spaghetti bulgogi]}