返回值类型写在最后面
可返回多个值
返回多个值时可以起名字,仅用于非常简单的函数
package main
import (
"fmt"
)
func main() {
q,r := div(5, 2)
fmt.Println(q, r)
}
func div(a, b int) (q, r int) {
q = a / b
r = a % b
return
}
匿名函数
package main
import "fmt"
func main() {
a := func(data string) {
fmt.Println(data)
}
a("我是匿名函数")
}
可变参数列表
package main
import (
"fmt"
)
func main() {
fmt.Println("1+2+...+5 =", sum(1, 2, 3, 4, 5))
}
func sum(numbers ...int) int {
s := 0
for i := range numbers {
s += numbers[i]
}
return s
}
package main
import (
"fmt"
)
func main() {
ar := []int{1, 2, 3, 4, 5}
fmt.Println("1+2+...+5 =", sum(ar...))
}
func sum(numbers ...int) int {
s := 0
for i := range numbers {
s += numbers[i]
}
return s
}
自执行函数
package main
import "fmt"
func main() {
(func() {
fmt.Println("我是自执行函数")
})()
}
闭包函数:返回值为函数
package main
import "fmt"
func main() {
closure()(4)
}
func closure() func(int) {
return func(num int) {
fmt.Println("闭包函数", num)
}
}
延迟调用函数
package main
import "fmt"
func main() {
defer delay()
fmt.Println(1)
fmt.Println(2)
fmt.Println(3)
}
func delay() {
fmt.Println("我是延迟调用函数")
}
函数作为参数
package main
import (
"fmt"
"runtime"
"math"
"reflect"
)
func main() {
fmt.Println("pow(3, 4) is:", apply(
func(a int, b int) int {
return int(math.Pow(
float64(a), float64(b)))
}, 3, 4))
}
func apply(op func(int, int) int, a, b int) int {
p := reflect.ValueOf(op).Pointer()
opName := runtime.FuncForPC(p).Name()
fmt.Printf("Calling function %s with args "+"(%d, %d)\n", opName, a, b)
return op(a, b)
}