Go - 將指標傳遞給函式



Go 程式語言允許你將指標傳遞給函式。若要執行此操作,只需將函式引數宣告為指標型別即可。

在以下示例中,我們將兩個指標傳遞給一個函式,並改變函式內部的值,該值會反映在呼叫函式中 -

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 */
}

編譯並執行上述程式碼後,將產生以下結果 -

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_pointers.htm
廣告
© . All rights reserved.