最近還有同學對defer有疑問的,理解這段輸出就好了

jemygraw發表於2018-11-16
package main

import (
    "fmt"
)

func deferTest() string {
    var name string
    defer func() {
        name = "first defer"
        fmt.Println("first set: ", name)
    }()

    defer func() {
        name = "second defer"
        fmt.Println("second set:", name)
    }()

    name = "func result"
    fmt.Println("func set:", name)
    return name
}

func main() {
    fmt.Println(deferTest())
}

相關文章