温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

怎么在Golang中对函数的参数进行传递

发布时间:2021-03-17 15:05:11 来源:亿速云 阅读:260 作者:Leah 栏目:编程语言

这期内容当中小编将会给大家带来有关怎么在Golang中对函数的参数进行传递,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。

默认情况下,Go编程语言使用调用通过值的方法来传递参数。在一般情况下,这意味着,在函数内码不能改变用来调用所述函数的参数。考虑函数swap()的定义如下。

/* function definition to swap the values */func swap(int x, int y) int {   var temp int
   temp = x /* save the value of x */   x = y    /* put y into x */   y = temp /* put temp into y */
   return temp;}


现在,让我们通过使实际值作为在以下示例调用函数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 */   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, y int) int {   var temp int
   temp = x /* save the value of x */   x = y    /* put y into x */   y = temp /* put temp into y */
   return temp;}


让我们把上面的代码放在一个C文件,编译并执行它,它会产生以下结果:

Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :100
After swap, value of b :200

这表明,参数值没有被改变,虽然它们已经在函数内部改变。

通过传递函数参数,即是拷贝参数的地址到形式参数的参考方法调用。在函数内部,地址是访问调用中使用的实际参数。这意味着,对参数的更改会影响传递的参数。

要通过引用传递的值,参数的指针被传递给函数就像任何其他的值。所以,相应的,需要声明函数的参数为指针类型如下面的函数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   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

这表明变化的功能以及不同于通过值调用的外部体现的改变不能反映函数之外。

上述就是小编为大家分享的怎么在Golang中对函数的参数进行传递了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI