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 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化