doutang1884 2017-10-11 15:50
浏览 11
已采纳

推迟现场分配是竞争条件吗?

Consider the following code:

type foo struct {
  bar string
}

func f() *foo {
  ret := &foo{"before"}
  defer func() { ret.bar = "after" }()
  return ret
}

func main() {
  fmt.Println(f()) // prints "&{after}"
}

The motivation is having to return a struct but some of the fields need to be set only before returning (e.g. a timestamp of when the function completed).

Is deferring the field assignation a race condition? Is it idiomatic? Is there a better way?

  • 写回答

2条回答 默认 最新

  • dongtan7639 2017-10-11 18:21
    关注

    The main benefit of using defer statement versus invoking something before returning from a function or routine is defer will run the statement even when a panic occurs before returning.

    Thus it is commonly used to clean up resources (such as closing a file or network connection) rather than to set state.

    The function below will not print or return "hello"

    func f() string {
            panic("omg")
            fmt.Println("hello")
            return "hello"
    }
    

    This code will print but won't return "hello"

    func f() string {
            defer fmt.Println("ello")
            panic("omg")
            return "hello"
    }
    

    To answer your question: No, it won't result in a race. Apart from the above difference, it is equivalent to calling something before the return statement.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?