35. Go - Variadic
Variadic functions can accept any number of inputs.
Example:
// variadic parameter must be only argument or the last argument.
// takes in 0 or more values
package main
import "fmt"
func main() {
printEverything("hello", "hello", "hello", "hello", "hello", "hello", "hello")
}
func printEverything(s ...string) {
if len(s) != 0 {
for i := 0; i < len(s); i++ {
fmt.Println(s[i])
}
fmt.Println("Length:", len(s))
}
}
Using variadic to get all values from a slice:
// "y..." means pull all value from y slice
package main
import "fmt"
func main() {
x := []int{1, 2, 3}
y := []int{4, 5, 6}
x = append(x, y...)
fmt.Println(x)
}
Using variadic of interface to get any type of value:
package main
import (
"fmt"
)
func main() {
variadicExample(1, "red", true, 10.5, []string{"foo", "bar", "baz"},
map[string]int{"apple": 23, "tomato": 13})
}
func variadicExample(i ...interface{}) {
for _, v := range i {
fmt.Println(v)
}
}
Using variadic to create dynamic arrays:
// let compiler figure out the length
package main
import "fmt"
func main() {
x := [...]int{1, 2, 3, 4, 5, 6, 7, 8, 9}
fmt.Println(x)
}
Comments
Post a Comment