当前位置:网站首页>Go defer little knowledge

Go defer little knowledge

2022-06-25 12:36:00 Velly_ zheng

Without further ado , First 3 A small example
 

func f() (result int) {
    defer func() {
        result++
    }()
    return 2
}

//
func f2() (r int) {
    t := 2
    defer func() {
        t = t + 1
    }()

    return t
}

func f3() (r int) {
    defer func(r int) {
        r = r + 1
    }(r)

    return 2
}

If you assign a value ,f1(), f2(), f3() Return respectively 3,2,2

 

If you want to understand , First of all, remember defer Two important features :

  1.       defer stay return xxx After the assignment ,return Execute before empty
  2.       defer If there is a reference , The parameter definition must be in defer Before , No. the parameter defaults to 0 Put it in
     

above f1() Easier to understand , because return 2 to result=2  Enter again defer function ,result++ Turned into 3, Last return, So the end result is 3

and f2() return t In fact, that is r=t, Get into defer, Changed the t Value , There is no change r Value , So the final result is 2

f3() return 2 It's actually r=2, Get into defer This is the time ,r=2 Is the result of execution , And compile time r There is no previous assignment , So the introduction defer Parameters r The default is 0, defer The medium pass parameter is 0, Internal variable with the same name r For the initial 0, Changed to 1; But internal variables with the same name r Not external f3() Return variable of r, It's just the same name

 

原网站

版权声明
本文为[Velly_ zheng]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202200529183845.html

随机推荐