How does defer and named return value work?

后端 未结 3 1298
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-14 06:04

I just started learning Go and I got confused with one example about using defer to change named return value in the The Go Blog - Defer, Panic, and Recover.

The exam

3条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-14 06:46

    I think the confusion is about function in function how about if you classified like this:

      func main() {
          fmt.Println(c()) //the result is 5
      }
    
      // the c function returned value is named j
      func c() (j int)  {
          defer changei(&j)
          return 6
      }
      func changei(j *int) {
          //now j is 6 because it was assigned by return statement 
          // and if i change guess what?! i changed the returned value
          *j--;
      }
    

    but if the return value is not named like this:

      func main() {
          fmt.Println(c()) //the result will become 6
      }
    
      // the c function returned value is not named at this time
      func c() int  {
          j := 1
          defer changei(&j)
          return 6
      }
      func changei(j *int) {
          //now j = 1
          // and if i change guess what?! it will not effects the returned value
          *j--;
      }
    

    I hope this will clear the confusion and that is how i did happy Go coding

提交回复
热议问题