tweak
This commit is contained in:
parent
b943fcfb74
commit
dd7a95399b
@ -1,18 +1,27 @@
|
|||||||
package main // Varadic functions can be called with any number of
|
package main // Varadic functions can be called with any number of
|
||||||
// trailing arguments.
|
// trailing arguments.
|
||||||
import "fmt"
|
import "fmt"
|
||||||
|
|
||||||
func add(nums ...int) int { // Varadic args are declared with `...type` and passed in as
|
func add(nums ...int) int { // Varadic args are declared with `...type` and
|
||||||
for _, num := range nums { // a slice.
|
fmt.Print(nums, " ") // passed in as a slice.
|
||||||
|
total := 0
|
||||||
|
for _, num := range nums {
|
||||||
total += num
|
total += num
|
||||||
}
|
}
|
||||||
return total
|
return total
|
||||||
}
|
}
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
fmt.Println(add(1, 2)) // Varadic functions can be called in the usual way.
|
fmt.Println(add(1, 2)) // Varadic functions can be called in the usual way.
|
||||||
fmt.Println(add(1, 2, 3, 4))
|
fmt.Println(add(1, 2, 3))
|
||||||
|
|
||||||
nums := []int{2, 3, 4, 5} // If you already have multiple args in a `slice`, apply
|
nums := []int{1, 2, 3, 4} // If you already have multiple args in a slice,
|
||||||
fmt.Println1(add(1, nums...)) // them to a varadic function using `func(arg, slice...)`.
|
fmt.Println(add(nums...)) // apply them to a varadic function using `
|
||||||
}
|
} // func(slice...)`.
|
||||||
|
|
||||||
|
/*
|
||||||
|
$ go run varadic.go
|
||||||
|
[1 2] 3
|
||||||
|
[1 2 3] 6
|
||||||
|
[1 2 3 4] 10
|
||||||
|
*/
|
||||||
|
Loading…
x
Reference in New Issue
Block a user