lean into examples

This commit is contained in:
Mark McGranaghan
2012-10-09 21:02:12 -07:00
parent 5d1775bdaa
commit 8daa226a48
130 changed files with 4 additions and 4 deletions

View File

@@ -0,0 +1,31 @@
// Varadic functions can be called with any number of
// trailing arguments. This is useful if you don't know
// number of arguments that will be needed for a function
// ahead of time.
package main
import "fmt"
// Varadic args are declared with `...type` and
// passed in as a slice.
func add(nums ...int) int {
fmt.Print(nums, " ")
total := 0
for _, num := range nums {
total += num
}
return total
}
func main() {
// Varadic functions can be called in the usual way.
fmt.Println(add(1, 2))
fmt.Println(add(1, 2, 3))
// If you already have multiple args in a slice,
// apply them to a varadic function using `
// func(slice...)`.
nums := []int{1, 2, 3, 4}
fmt.Println(add(nums...))
}

View File

@@ -0,0 +1,4 @@
$ go run varadic-functions.go
[1 2] 3
[1 2 3] 6
[1 2 3 4] 10