dqask02082 2014-02-07 17:32
浏览 49

Golang Defer可以对调用者/外部函数起作用?

Is it possible to defer to the end of an outer function?

// normal transaction
func dbStuff(){
    db.Begin()
    ...
    db.Commit()
}

// normal transaction w/ defer
func dbStuff(){
    db.Begin()
    defer db.Commit()
    ...
}

Is this possible?

// can you defer to caller / outer function?
func dbStuff(){
    db.Trans()
    ...
}

// will Commit() when dbStuff() returns
func (db Db) Trans(){
    db.Begin()
    defer db.Commit() // to caller/outer function
}
  • 写回答

1条回答 默认 最新

  • dongmen1925 2014-02-09 09:56
    关注

    According to the specification, it's not possible:

    A "defer" statement invokes a function whose execution is deferred to the moment the surrounding function returns, either because the surrounding function executed a return statement, reached the end of its function body, or because the corresponding goroutine is panicking.

    (emphasis mine)

    Update: Apart from that, it would not be a good idea either – one of the strengths of Go is "what you see is what you get". Deferring functions from inner functions to outer functions would create 'invisible' changes in your control flow.

    评论

报告相同问题?

悬赏问题

  • ¥15 目详情-五一模拟赛详情页
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line