Go course

Slicesmake, len, cap, and append

Go

Display

Theme

Slices · Test exercise

make, len, cap, and append

Creating a slice with make

If you know roughly how many elements you'll need, create the slice with make:

kursi := make([]bool, 10)        // len 10, semua false
antrean := make([]string, 0, 50) // len 0, cap 50
  • len(s): the number of elements currently in use.
  • cap(s): the capacity of the array behind the slice, that is, how many elements fit before a new array is needed.

Adding elements with append

append adds elements at the end and returns a new slice, so always keep the result:

var pesanan []string // nil, len 0
pesanan = append(pesanan, "Nasi Goreng")
pesanan = append(pesanan, "Es Teh", "Kerupuk") // bisa beberapa sekaligus
fmt.Println(len(pesanan)) // 3

You can append several elements at once, as the second call shows. If there's still enough capacity, append writes to the same array. If not, Go allocates a new, bigger array (usually twice the size), copies the contents over, then adds the new elements. That's why the result of append must be stored back.

Reserving capacity with make([]T, 0, n) avoids repeated allocations when you already know how many elements there will be.

A nil slice is safe to use with len, range, and append, so you don't need to initialize it first.

Task

An online store's warehouse system. Complete:

  1. func nomorResi(awal, n int) []int: create a slice holding n consecutive tracking numbers starting from awal. Use make([]int, 0, n) and then append. The result must have len == n and cap == n. Example: nomorResi(1001, 3) → [1001 1002 1003].
  2. func stokMenipis(stok []int, batas int) []int: return a slice of the indexes of items whose stock is less than batas, in order. Example: stokMenipis([]int{12, 3, 0, 25, 4}, 5) → [1 2 4].
main.go
package main

import "fmt"

func nomorResi(awal, n int) []int {
	// TODO: make([]int, 0, n) lalu append
	return nil
}

func stokMenipis(stok []int, batas int) []int {
	// TODO: kumpulkan indeks dengan append
	return nil
}

func main() {
	resi := nomorResi(1001, 5)
	fmt.Println(resi, len(resi), cap(resi))
	fmt.Println(stokMenipis([]int{12, 3, 0, 25, 4}, 5))
}

Output

Go runtime not loaded yet

Press Run to see the output, or Submit to check your code.

Ctrl/Cmd + Enter: Run · Ctrl/Cmd + Shift + Enter: Submit · Ctrl/Cmd + S: tidy the code (gofmt)