package main import (
"fmt"
"time"
) func sum(a ...int) int {
defer trace("sum")() // note:不要忘记defer语句后的圆括号,否则本该在进入时执行的操作会在退出时执行,而本该在退出时执行的,永远不会执行
total :=
for _, val := range a {
total += val
}
return total
} func trace(msg string) func() {
start := time.Now()
fmt.Printf("enter %s\n", msg)
return func() {
fmt.Printf("exit %s (%s)\n", msg, time.Since(start))
}
} func main() {
count := sum(, , )
fmt.Printf("%d\n", count)
}
执行结果:
enter sum
exit sum (.764µs)
利用defer修改函数的返回值:
package main import (
"fmt"
"time"
) func sum(a, b int) (result int) {
//defer trace("sum")() // note:不要忘记defer语句后的圆括号,否则本该在进入时执行的操作会在退出时执行,而本该在退出时执行的,永远不会执行
defer func() { result += a }() //被延时执行的匿名函数甚至可以修改函数返回给调用者的返回值
result =
result += a
result += b
return result
} func trace(msg string) func() {
start := time.Now()
fmt.Printf("enter %s\n", msg)
return func() {
fmt.Printf("exit %s (%s)\n", msg, time.Since(start))
}
} func main() {
count := sum(, )
fmt.Printf("%d\n", count)
}
执行结果:
[root@docker pro]# go run arg.go
[root@docker pro]# go run arg.go