SHARE
TWEET

Untitled

a guest Jul 16th, 2019 54 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // 闭包 trap
  2. var rmdirs []func()
  3. for _, d := range tempDirs() {
  4.     dir := d // 不能删除,否则循环删除的是同一个目录
  5.     os.MkdirAll(dir, 0755)
  6.     rmdirs = append(rmdirs, func() {
  7.         os.RemoveAll(dir)
  8.     })
  9. }
  10.  
  11. for _, rmdir := range rmdirs {
  12.     rmdir()
  13. }
  14.  
  15. // 因为 for 循环引入了新的词法块, d 在这个词法块中被声明,而闭包(函数值)中记录的是循环变量的内存地址,而不是某一时刻的值,所以引入一个新的变量,将 d 赋值给 dir
  16. // 这并不是循环的问题,而是闭包(函数值)等待循环结束之后才执行
  17. // 另外的解决方法,将 d 作为参数传递给闭包(函数值)
  18. for _, dir := range tempDirs() {
  19.     os.MkdirAll(dir, 0755)
  20.     rmdirs = append(rmdirs, func(dir string) {
  21.         os.RemoveAll(dir)
  22.     }(dir))
  23. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top