eddycjy / blog

煎鱼的博客,有点忙,传送门:https://eddycjy.com
3.05k stars 431 forks source link

请教一下,这个程序问题在哪里? #31

Closed aQuaYi closed 5 years ago

aQuaYi commented 5 years ago

https://github.com/EDDYCJY/blog/blob/master/golang/pkg/2019-05-26-Go-defer.md

···go package main

import( "fmt" )

func main(){ fmt.Println(exchangeBack(0,1)) }

func exchangeBack(a,b int) (int,int) { defer func(){ a,b = b,a }() return b, a } ···

输出是 1,0 并非期望的 0,1

aQuaYi commented 5 years ago

想要实现 交换回来的效果,需要按照以下的方法来做。

···go package main

import( "fmt" )

func main(){ fmt.Println(exchangeBack(0,1)) }

func exchangeBack(a,b int) (c,d int) { c,d = b,a
defer func(){ c,d = d,c }() return
} ···

navono commented 5 years ago

下面这个是返回命名变量。

aQuaYi commented 5 years ago

@navono 我记得 Go 语言传递的都是值呀! 这两个程序的差异在哪里呢?

navono commented 5 years ago

可以看下这篇文章。

aQuaYi commented 5 years ago

@navono 谢谢,我果然遇到了坑