In Go, function can return multi value:
func addAndSubstract(a int, b int) (int, int) {
return a+b, a-b
}
It is also possible to define named return value:
func addAndSubstract2(a int, b int) (addRes int, subRes int) {
addRes = a + b
subRes = a - b
return
}
Usage:
package main
import "fmt"
func main() {
addRes, subRes := addAndSubstract(2,3)
fmt.Println(addRes, subRes)
}
You can also omit the variable definiation with _
:
func main() {
_, subRes := addAndSubstract(2,3)
fmt.Println(subRes)
}
Pointer *
:
In GO, normally you pass value
to function params. Different from some other programming language, you pass the reference to the function.
If you somehow want to mutate the value, you can use pointer.
func birthday(age *int) {
*age++
}
Usage:
package main
import "fmt"
func birthday(age *int) {
*age++
}
func main() {
age := 22
birthday(&age) // pass the reference
fmt.Println(age) // 23
}