溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

怎么在Golang中對函數的參數進行傳遞

發布時間:2021-03-17 15:05:11 來源:億速云 閱讀:318 作者: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

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女