要通过引用传递的值,参数的指针被传递给函数就像任何其他的值 。所以,相应的,需要声明函数的参数为指针类型如下面的函数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语言怎么加减乘除的信息别忘了在本站进行查找喔 。
推荐阅读
- linux用户隶属于命令,linux 用户命令
- 关于棋牌游戏开发培训的信息
- pip工具安装python,pip工具安装第三方模块需不需要联网
- python递归函数次数 python 递归函数
- 传统媒体稿如何转新媒体稿,传统媒体转战新媒体的人
- 包含重启电脑怎么从u盘启动不了怎么办啊的词条
- 硬盘盒中硬盘怎么装系统,硬盘盒中硬盘怎么装系统教程
- vb.net美化控件 vb程序界面美化
- k570n更换什么cpu,k570n拆机