This is a creation in Article, where the information may have evolved or changed.
See Code:
PackageMainImport("FMT")funcMain() {varWhatever [5]struct{} forI: =RangeWhatever {fmt.Println(i)}//part 1 forI: =RangeWhatever {defer func() {FMT.Println(i)} () }//part 2 forI: =RangeWhatever {defer func(nint) {FMT.Println(n)} (i)}//part 3}
Part 1 does not have to explain what, at a glance, is typical of a go language closure, which captures the variable "I", for the part 2, note that the "reference" is holding the "references" not a copy yo! So when Part2 's for loop ends, the value of the variable "i" is exactly 4, so the output of the closure is 4. For Part 3, although it is also a closure, but does not capture the variable "I", but instead of the normal way to call the closure, and for the form: defer f (e) of the statement, the F function or closure is not immediately executed, but its parameter expression will be evaluated immediately, is evaluated, such as: F (0), F ( 1) ... f (4); and since the defer call is executed in a state-of-the-art manner, the output of the PART3 is: 4,3,2,1,0; so part2 is executed after part3, so the output is reversed!
Original: Http://stackoverflow.com/questions/16010694/how-golangs-defer-capture-closures-parameter
Note: This article is only my personal notes, if there are errors and omissions, please correct me, study together, my e-mail: htyu_0203_39@sina.com