這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
package mainimport "fmt"// Here's a function that will take an arbitrary number// of `ints` as arguments.func sum(nums ...int) {fmt.Print(nums, " ")total := 0for _, num := range nums {total += num}fmt.Println(total)}func main() {// Variadic functions can be called in the usual way// with individual arguments.sum(1, 2)sum(1, 2, 3)// If you already have multiple args in a slice,// apply them to a variadic function using// `func(slice...)` like this.nums := []int{1, 2, 3, 4}sum(nums...)}
12345678910111213141516171819202122232425262728 |
package main import "fmt" // Here's a function that will take an arbitrary number// of `ints` as arguments.func sum(nums ...int) {fmt.Print(nums, " ")total := 0for _, num := range nums {total += num}fmt.Println(total)} func main() { // Variadic functions can be called in the usual way// with individual arguments.sum(1, 2)sum(1, 2, 3) // If you already have multiple args in a slice,// apply them to a variadic function using// `func(slice...)` like this.nums := []int{1, 2, 3, 4}sum(nums...)} |
輸出的值:
[1 2] 3[1 2 3] 6[1 2 3 4] 10
123 |
[1 2] 3[1 2 3] 6[1 2 3 4] 10 |
go 的變參函數