1 package main 2 3 import ( 4 "fmt" 5 "time" 6 ) 7 8 func sum(a ...int) int { 9 defer trace("sum")() // note:不要忘记defer语句后的圆括号,否则本该在进入时执行的操作会在退出时执行,而本该在退出时执行的,永远不会执行 10 total := 0 11 for _, val := range a { 12 total += val 13 } 14 return total 15 } 16 17 func trace(msg string) func() { 18 start := time.Now() 19 fmt.Printf("enter %s\n", msg) 20 return func() { 21 fmt.Printf("exit %s (%s)\n", msg, time.Since(start)) 22 } 23 } 24 25 func main() { 26 count := sum(3, 5, 9) 27 fmt.Printf("%d\n", count) 28 }
执行结果:
1 enter sum 2 exit sum (194.764µs) 3 17
利用defer修改函数的返回值:
1 package main 2 3 import ( 4 "fmt" 5 "time" 6 ) 7 8 func sum(a, b int) (result int) { 9 //defer trace("sum")() // note:不要忘记defer语句后的圆括号,否则本该在进入时执行的操作会在退出时执行,而本该在退出时执行的,永远不会执行 10 defer func() { result += a }() //被延时执行的匿名函数甚至可以修改函数返回给调用者的返回值 11 result = 0 12 result += a 13 result += b 14 return result 15 } 16 17 func trace(msg string) func() { 18 start := time.Now() 19 fmt.Printf("enter %s\n", msg) 20 return func() { 21 fmt.Printf("exit %s (%s)\n", msg, time.Since(start)) 22 } 23 } 24 25 func main() { 26 count := sum(3, 8) 27 fmt.Printf("%d\n", count) 28 }
执行结果:
1 [root@docker pro]# go run arg.go 2 [root@docker pro]# go run arg.go 3 14