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:
func totalBelanja(diskonPersen int, harga ...int) int: add up all theharga(prices), then subtract a discount oftotal * diskonPersen / 100(integer division).func gabungKeranjang(keranjang ...[]string) []string: merge several carts (each a[]string) into a single slice, keeping their order. Useappendwith the...spread.- In
main, calltotalBelanjawith thehargaPromoslice 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].