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
nilslice is safe to use withlen,range, andappend, so you don't need to initialize it first.
Task
An online store's warehouse system. Complete:
func nomorResi(awal, n int) []int: create a slice holdingnconsecutive tracking numbers starting fromawal. Usemake([]int, 0, n)and thenappend. The result must havelen == nandcap == n. Example:nomorResi(1001, 3)→[1001 1002 1003].func stokMenipis(stok []int, batas int) []int: return a slice of the indexes of items whose stock is less thanbatas, in order. Example:stokMenipis([]int{12, 3, 0, 25, 4}, 5)→[1 2 4].