golang的defer和返回值


1. defer中修改隐式返回值

package main
import "fmt"

func main() {
    fmt.Println("main call f1:", f1())
}

func f1() int {
    var i int
    defer func() {
        i++
        fmt.Println("defer call:", i)
    }()
    return i
}

运行结果:

defer call: 1
main call f1: 0

defer里的函数没有改变返回值

2. defer中修改显式返回值

package main
import "fmt"

func main() {
    fmt.Println("main call f2:", f2())
}

func f2() (ret int) {
    defer func() {
        ret++
        fmt.Println("defer call:", ret)
    }()
    return 10 // 相当于ret=10
}

运行结果:

defer call: 11
main call f2: 11

defer里的函数改变了返回值

  • 注意:

    当返回值是指针时,无论返回值是隐式还是显式都受影响;

/latefirstcmt/22