国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Golang > 正文

Go語言中函數的參數傳遞與調用的基本方法

2020-04-01 19:12:27
字體:
來源:轉載
供稿:網友
這篇文章主要介紹了Go語言中函數的參數傳遞與調用的基本方法,是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文件,編譯并執行它,它會產生以下結果:
  1. Before swap, value of a :100 
  2. Before swap, value of b :200 
  3. After swap, value of a :100 
  4. 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文件,編譯并執行它,它會產生以下結果:
  1. Before swap, value of a :100 
  2. Before swap, value of b :200 
  3. After swap, value of a :200 
  4. After swap, value of b :100 
 

這表明變化的功能以及不同于通過值調用的外部體現的改變不能反映函數之外。


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 高密市| 鹿邑县| 腾冲县| 玉门市| 二连浩特市| 浠水县| 白朗县| 班玛县| 青海省| 蒙阴县| 顺平县| 伊吾县| 抚松县| 曲水县| 卫辉市| 乌什县| 常山县| 靖远县| 武冈市| 绥宁县| 和平县| 西宁市| 平安县| 陇南市| 清水河县| 林州市| 巧家县| 焦作市| 永修县| 上饶县| 岳阳县| 农安县| 搜索| 曲水县| 长泰县| 保定市| 津市市| 阿合奇县| 寿宁县| 合水县| 峨边|