Go Tutorial menu

Go Arrays, Slices and Maps

Arrays, slices and maps let one variable hold many values.

Arrays

An array has a fixed length that is part of its type. [3]int is an array of exactly 3 integers.

Example

go
package main

import "fmt"

func main() {
	var marks [3]int
	marks[0] = 78
	marks[1] = 91
	fmt.Println(marks)

	days := [3]string{"Mon", "Tue", "Wed"}
	fmt.Println(days[1], len(days))
}
Output
[78 91 0]
Tue 3

The third mark is 0, the zero value. Arrays are rarely used directly; slices are much more common.

Slices

A slice is like an array that can grow. Its type has no number: []string.

Example

go
package main

import "fmt"

func main() {
	cart := []string{"Rice", "Daal"}
	cart = append(cart, "Oil", "Tea")
	fmt.Println(cart)
	fmt.Println(len(cart))

	fmt.Println(cart[1:3])
	fmt.Println(cart[:2])
	fmt.Println(cart[2:])
}
Output
[Rice Daal Oil Tea]
4
[Daal Oil]
[Rice Daal]
[Oil Tea]
  • append returns a new slice, so always write cart = append(cart, ...).
  • cart[1:3] takes items from index 1 up to, but not including, index 3.
ExpressionGives
s[a:b]Items from a to b-1
s[:b]From the start to b-1
s[a:]From a to the end
len(s)Number of items
make([]int, 5)A new slice of five zeros

A slice made from another slice shares the same data. Changing part[0] changes the original too. Use copy() when you need a separate copy.

Maps

A map stores key: value pairs. The type map[string]int has string keys and int values.

Example

go
package main

import "fmt"

func main() {
	prices := map[string]int{
		"Samosa": 40,
		"Chai":   60,
	}
	prices["Paratha"] = 80
	fmt.Println(prices["Chai"])
	fmt.Println(len(prices))

	delete(prices, "Samosa")
	fmt.Println(prices)

	price, ok := prices["Burger"]
	fmt.Println(price, ok)

	if p, found := prices["Paratha"]; found {
		fmt.Println("Paratha costs Rs", p)
	}
}
Output
60
3
map[Chai:60 Paratha:80]
0 false
Paratha costs Rs 80
  • Reading a missing key returns the zero value, here 0.
  • The comma ok form value, ok := m[key] tells you if the key really exists.
  • fmt.Println prints maps with keys sorted, but a range loop over a map visits keys in a random order.

Creating an Empty Map

Example

go
stock := make(map[string]int)
stock["Pens"] = 25

A map must be created with make or a literal before you add keys. Writing to a nil map crashes the program.

Looping over a Slice and a Map

Example

go
package main

import "fmt"

func main() {
	scores := []int{70, 85, 90}
	total := 0
	for _, s := range scores {
		total += s
	}
	fmt.Println("Average:", total/len(scores))

	ages := map[string]int{"Ali": 20}
	for name, age := range ages {
		fmt.Println(name, "is", age)
	}
}
Output
Average: 81
Ali is 20

Exercise

Exercise

If s := []int{10, 20, 30, 40}, what is s[1:3]?

Learn Go with a teacher

Join the Python Programming course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp