douhu5837 2016-05-06 13:22
浏览 30
已采纳

为什么在范围循环中延迟以相反的顺序调用?

I've run across an answer on a question about "reverse range" and I was going to down-vote it as it seemed ridiculously wrong but checked and it actually works(!):

https://play.golang.org/p/4K2fDlSoCm

package main

import (
    "fmt"
)

func main() {
    s := []int{1, 2, 3, 4, 5}
    for i, _ := range s {
        defer fmt.Println(s[i])
    }
}

And the output is:

5
4
3
2
1
Program exited.

Any ideas why it works this way? Am I right it's not guaranteed to be executed exactly in the reverse order? Also I don't think it's a good way to write programs but curious to find why are we getting this result.

  • 写回答

1条回答 默认 最新

  • dongtang8678 2016-05-06 13:27
    关注

    defer is a LIFO, or a stack - it is guaranteed to executed in reverse order. It gets the first defer and puts it on some internal stack (probably, I don't know the gory details), and then puts the next defer on top of that one, and then when it hits the end of the function, it unwinds, starting at the top. It seems contrived in a for-loop (I know this is Go's example, not yours), but in other cases where one function depends upon the clean-up of some other function, it makes more sense why it SHOULD be, and hence IS, guaranteed to be reverse order of execution.

    Here's a different example, all pseudo-code, but hopefully the point is clear.

    open stream1
    defer close stream1
    defer write stream1 "stream2 better be closed, or we are in trouble..."
    open stream2
    defer close stream2
    defer stream2 "this is the last you'll ever hear from stream2"
    
    connect stream2 to stream1
    
    write stream2 "hey, we are in stream2, this feeds into stream1"
    

    Should print something like:

    "hey, we are in stream2, this feeds into stream1"
    "this is the last you'll ever hear from stream2"
    "stream2 better be closed, or we are in trouble..."
    

    If you didn't have guarantees about reverse ordering, you couldn't be sure stream1 was still open during your defer stream2 write.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题