[Golang]variadic function

This is the first time I have heard of this function, this is the same as python’s args for unknown number of positional arguments in a function.

package main

import "fmt"

func main() {
	total1 := sum(1,2,3)
	nums := []int{10, 12, 13, 14}
	/*
	the nums... will list down the elements of a slice which is the same
	as this:
	for _, v := nums {
		fmt.Println(v)
	}
	 */
	total2 := sum(nums...)
	fmt.Println("First total: ", total1)
	fmt.Println("Second total by adding elements in slice: ", total2)
}

// variadic functions to take in unknown number of n.
// This is the same as the python args for positional arguments.
func sum(n ...int) int {
	total := 0
	for _, v := range n {
		total += v
	}
	return total
}
Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s