Go Functions
Go functions, multiple return values, and variadic parameters
Functions
Use func to define a function and return to specify its return value.
package main
import "fmt"
func add(x int, y int) int {
return x + y
}
func main() {
fmt.Println(add(5, 3)) // => 8
}
Output:
8
Multiple return values
A function can return multiple values. Group the return types with parentheses.
func addMinus(x int, y int) (int, int) {
return x + y, x - y
}
func main() {
add, min := addMinus(8, 5)
fmt.Println(add, min)
}
Output:
13 3
Use the blank identifier _ to ignore an unnecessary return value.
_, y := funcA()
Variadic parameters
Use ... to define a variadic parameter.
package main
import "fmt"
func funcA(a int, b ...int) {
fmt.Printf("a=%d\n", a)
for i, num := range b {
fmt.Printf("b[%d]=%d\n", i, num)
}
}
func main() {
funcA(1, 2, 3, 4, 5)
}
Output:
a=1
b[0]=2
b[1]=3
b[2]=4
b[3]=5