github.com/jd-ly/tools@v0.5.7/go/ssa/interp/testdata/defer.go (about)

     1  package main
     2  
     3  // Tests of defer.  (Deferred recover() belongs is recover.go.)
     4  
     5  import "fmt"
     6  
     7  func deferMutatesResults(noArgReturn bool) (a, b int) {
     8  	defer func() {
     9  		if a != 1 || b != 2 {
    10  			panic(fmt.Sprint(a, b))
    11  		}
    12  		a, b = 3, 4
    13  	}()
    14  	if noArgReturn {
    15  		a, b = 1, 2
    16  		return
    17  	}
    18  	return 1, 2
    19  }
    20  
    21  func init() {
    22  	a, b := deferMutatesResults(true)
    23  	if a != 3 || b != 4 {
    24  		panic(fmt.Sprint(a, b))
    25  	}
    26  	a, b = deferMutatesResults(false)
    27  	if a != 3 || b != 4 {
    28  		panic(fmt.Sprint(a, b))
    29  	}
    30  }
    31  
    32  // We concatenate init blocks to make a single function, but we must
    33  // run defers at the end of each block, not the combined function.
    34  var deferCount = 0
    35  
    36  func init() {
    37  	deferCount = 1
    38  	defer func() {
    39  		deferCount++
    40  	}()
    41  	// defer runs HERE
    42  }
    43  
    44  func init() {
    45  	// Strictly speaking the spec says deferCount may be 0 or 2
    46  	// since the relative order of init blocks is unspecified.
    47  	if deferCount != 2 {
    48  		panic(deferCount) // defer call has not run!
    49  	}
    50  }
    51  
    52  func main() {
    53  }