funclargest(nums []int) { defer finished() fmt.Println("Started finding largest") max := nums[0] for _, v := range nums { if v > max { max = v } } fmt.Println("Largest number in", nums, "is", max) }
funcmain() { p := person { firstName: "John", lastName: "Smith", } defer p.fullName() fmt.Printf("Welcome ") }
在上面的程序中,我们在第22行延迟了一个方法调用。该程序的其余部分是不言自明的。这个程序的输出:
1
Welcome John Smith
参数评估
延迟函数的参数在执行延迟语句时被评估,而不是在实际函数调用时被评估。
让我们通过一个例子来理解这一点。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
package main
import ( "fmt" )
funcprintA(a int) { fmt.Println("value of a in deferred function", a) } funcmain() { a := 5 defer printA(a) a = 10 fmt.Println("value of a before deferred function call", a)
func(r rect) area(wg *sync.WaitGroup) { defer wg.Done() if r.length < 0 { fmt.Printf("rect %v's length should be greater than zero\n", r) return } if r.width < 0 { fmt.Printf("rect %v's width should be greater than zero\n", r) return } area := r.length * r.width fmt.Printf("rect %v's area %d\n", r, area) }
funcmain() { var wg sync.WaitGroup r1 := rect{-67, 89} r2 := rect{5, -67} r3 := rect{8, 9} rects := []rect{r1, r2, r3} for _, v := range rects { wg.Add(1) go v.area(&wg) } wg.Wait() fmt.Println("All go routines finished executing") }
这个程序输出。
1 2 3 4
rect {8 9}'s area 72 rect {-67 89}'s length should be greater than zero rect {5 -67}'s width should be greater than zero All go routines finished executing