douxiong2999 2019-08-12 16:54
浏览 42
已采纳

去延迟函数返回值

func main() {

    println(DeferFunc1(1))
    println(DeferFunc2(1))
    println(DeferFunc3(1))
}

func DeferFunc1(i int) (t int) {
    t = i
    defer func() {
        t += 3
    }()
    return t
}

func DeferFunc2(i int) int {
    t := i
    defer func() {
        t += 3
    }()
    return t
}

func DeferFunc3(i int) (t int) {
    defer func() {
        t += i
    }()
    return 2
}

Above code will print: 4 1 3. Can anyone explain this? Of course, DeferFunc1 should return 4. But why will DeferFunc2 and DeferFunc3 will return 1 and 3 respectively? Is that about closure or variable scope in Go?

  • 写回答

1条回答 默认 最新

  • dongliang1893 2019-08-12 17:15
    关注

    If DeferFunc1 makes sense to you then DeferFunc3 should as well as they illustrate the same concept, namely that you can modify a named return value.

    In DeferFunc1 you are adding 3 to 1 in your defer yielding your expected 4.
    In DeferFunc3 you are adding 1 to 2 in your defer yielding 3. A naked return here, or a return of t would get you to 4. But in this case, t is assigned the value of 2 right before your defer runs, so you get 3.
    In DeferFunc2 you are not using a named return, so you cannot take advantage of this technique.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?