Tsallaka zuwa abun ciki
Justice Tech School

Variadic Functions and Method Values

A variadic parameter collects extra arguments into a slice. Pass an existing slice with s... . Methods can be used as values.

Example
package main

import "fmt"

func sum(nums ...int) int {
	t := 0
	for _, n := range nums {
		t += n
	}
	return t
}

type Greeter struct{ Name string }

func (g Greeter) Hi() string { return "Hi " + g.Name }

func main() {
	fmt.Println(sum(1, 2, 3), sum([]int{4, 5}...))
	f := Greeter{"Ada"}.Hi
	fmt.Println(f())
}

Result

6 9
Hi Ada

Exercise

Pass a slice as arguments.

sum(nums)

Quiz Test

What does ...int collect?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.