Golang: Pass Array Elements to Function

By Xah Lee. Date: .

If you have a Array (or Slice) and you want to pass its elements to function as arguments, you can do:

ff(array ...)

package main

import "fmt"

// add all args
func ff(args ...int) int {
	var total = 0
	for _, v := range args {
		total += v
	}
	return total
}

func main() {
	// slice
	var x = []int{3, 7, 10}

	// slice to args
	fmt.Printf("%v\n", ff(x...)) // 20
}

golang function

Golang

Compile and Run

String

Types and Values

Branching and Loop

Data Structure

Function

Misc

Examples

Reference