如果将参数作为defer要运行的函数,则无法直接实现defer的延迟判断
例如:
package main
import (
"fmt"
)
func DoRollBack(success bool) {
if !success {
fmt.Println("Roll Back")
}
}
func main() {
success := false
defer DoRollBack(success)
// do something
// if no errors occurred, set success to true
success = true
}
分析:
无论defer之后怎么修改success的值都不生效,因为bool不是引用类型,传值无法同步修改,只有引用类型才可以,需要传指针,但是传指针又不够优雅
package main
import (
"fmt"
)
func DoRollBack() {
fmt.Println("Roll Back")
}
func main() {
success := false
defer func() {
if !success {
DoRollBack()
}
}()
// do something
// if no errors occurred, set success to true
success = true
}