1
0
mirror of https://github.com/chai2010/advanced-go-programming-book.git synced 2025-05-24 04:22:22 +00:00

Merge pull request #47 from jiayx/master

修复 ch1-04 的输出错误,并将换行从 CRLF 替换为 LF
This commit is contained in:
chai2010 2018-01-11 17:37:00 +08:00 committed by GitHub
commit 93dda51f89
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -88,12 +88,12 @@ func main() {
}
}
// Output:
// 4
// 4
// 4
// 3
// 3
// 3
```
因为是闭包,在`for`迭代语句中,每个`defer`语句延迟执行的函数引用的都是同一个`i`迭代变量,在循环结束后这个变量的值为4因此最终输出的都是4
因为是闭包,在`for`迭代语句中,每个`defer`语句延迟执行的函数引用的都是同一个`i`迭代变量,在循环结束后这个变量的值为3因此最终输出的都是3
修复的思路是在每轮迭代中为每个`defer`函数生成独有的变量。可以用下面两种方式: