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

去延迟函数返回值

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?

图片转代码服务由CSDN问答提供 功能建议

  func main(){
 
 println(DeferFunc1(1))
 println(DeferFunc2  (1))
 println(DeferFunc3(1))
} 
 
func DeferFunc1(i int)(t int){
t = i 
 defer func(){
t + = 3 
}(  )
返回t 
} 
 
func DeferFunc2(i int)int {
t:= i 
延迟func(){
t + = 3 
}()
返回t 
} 
  
func DeferFunc3(i int)(t int){
延迟func(){
t + = i 
}()
返回2 
} 
   
 
  

上面的代码将打印: 4 1 3 。 谁能解释一下? 当然, DeferFunc1 应该返回 4 。 但是为什么 DeferFunc2 DeferFunc3 分别返回 1 3 ? 是关于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.

    已采纳该答案
    打赏 评论

相关推荐 更多相似问题