Go course

SlicesVariadic Functions and the ... Operator

Go

Display

Theme

Slices · Test exercise

Variadic Functions and the ... Operator

A variadic function accepts a varying number of arguments for its last parameter. Mark its type with ...:

func jumlahkan(angka ...int) int {
	total := 0
	for _, a := range angka {
		total += a
	}
	return total
}

jumlahkan()           // 0
jumlahkan(5)          // 5
jumlahkan(1, 2, 3, 4) // 10

Inside the function, angka is an ordinary slice ([]int). If there are no arguments, the slice is nil with a length of 0.

Only the last parameter can be variadic, and it can come after regular parameters:

func catat(level string, pesan ...string)

You've already used variadic functions plenty of times: fmt.Println(a ...any) and append(s []T, elemen ...T).

The spread operator

If your data is already a slice, "spread" it into the variadic parameter with ... after the slice name:

belanja := []int{12000, 8000, 5000}
fmt.Println(jumlahkan(belanja...)) // 25000

This is also how you join two slices with append:

a := []string{"x", "y"}
b := []string{"z"}
a = append(a, b...) // [x y z]

Task

An online store checkout. Complete:

  1. func totalBelanja(diskonPersen int, harga ...int) int: add up all the harga (prices), then subtract a discount of total * diskonPersen / 100 (integer division).
  2. func gabungKeranjang(keranjang ...[]string) []string: merge several carts (each a []string) into a single slice, keeping their order. Use append with the ... spread.
  3. In main, call totalBelanja with the hargaPromo slice using the spread operator (see the TODO). This part isn't tested, but try running it.

Example: totalBelanja(10, 50000, 30000, 20000) → 90000. gabungKeranjang([]string{"buku"}, []string{"pena", "map"}) → [buku pena map].

main.go
package main

import "fmt"

func totalBelanja(diskonPersen int, harga ...int) int {
	// TODO: jumlahkan harga lalu kurangi diskon
	return 0
}

func gabungKeranjang(keranjang ...[]string) []string {
	// TODO: gabungkan semua keranjang dengan append(hasil, k...)
	return nil
}

func main() {
	fmt.Println(totalBelanja(10, 50000, 30000, 20000))

	hargaPromo := []int{15000, 25000, 60000}
	// TODO: panggil totalBelanja dengan diskon 5 dan hargaPromo menggunakan spread
	fmt.Println(hargaPromo)

	fmt.Println(gabungKeranjang([]string{"buku"}, []string{"pena", "map"}))
}

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)