go语言怎么加减乘除 go语言技巧( 三 )


要通过引用传递的值,参数的指针被传递给函数就像任何其他的值 。所以,相应的,需要声明函数的参数为指针类型如下面的函数swap(),它的交换两个整型变量的值指向它的参数 。
代码如下:
/* function definition to swap the values */
func swap(x *int, y *int) {
var temp int
temp = *x/* save the value at address x */
*x = *y/* put y into x */
*y = temp/* put temp into y */
}
现在,让我们调用函数swap()通过引用作为在下面的示例中传递数值:
代码如下:
package main
import "fmt"
func main() {
/* local variable definition */
var a int = 100
var b int= 200
fmt.Printf("Before swap, value of a : %d\n", a )
fmt.Printf("Before swap, value of b : %d\n", b )
/* calling a function to swap the values.
* a indicates pointer to a ie. address of variable a and
* b indicates pointer to b ie. address of variable b.
*/
swap(a, b)
fmt.Printf("After swap, value of a : %d\n", a )
fmt.Printf("After swap, value of b : %d\n", b )
}
func swap(x *int, y *int) {
var temp int
【go语言怎么加减乘除 go语言技巧】temp = *x/* save the value at address x */
*x = *y/* put y into x */
*y = temp/* put temp into y */
}
让我们把上面的代码放在一个C文件,编译并执行它,它会产生以下结果:
Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :200
After swap, value of b :100
这表明变化的功能以及不同于通过值调用的外部体现的改变不能反映函数之外 。
go语言怎么加减乘除的介绍就聊到这里吧,感谢你花时间阅读本站内容,更多关于go语言技巧、go语言怎么加减乘除的信息别忘了在本站进行查找喔 。

推荐阅读