gpt4 book ai didi

Golang 推迟对调用者/外部函数采取行动?

转载 作者:IT王子 更新时间:2023-10-29 01:34:01 28 4
gpt4 key购买 nike

是否可以延迟到外部函数的末尾?

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

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

这可能吗?

// 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
}

最佳答案

根据规范,不可能:

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.

(强调我的)

更新:除此之外,这也不是一个好主意——Go 的优势之一是“所见即所得”。将函数从内部函数延迟到外部函数会在您的控制流中产生“不可见”的变化。

关于Golang 推迟对调用者/外部函数采取行动?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21634192/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com