Golang 向函数传递指针

Go编程语言中的指针是一个变量,用来存储另一个变量的内存地址。你也可以像变量一样把指针传给函数。有两种方法可以做到这一点,如下。

创建一个指针并简单地将其传递给函数

在下面的程序中,我们正在使用一个函数ptf ,它有整数类型的指针参数,指示函数只接受指针类型的参数。基本上,这个函数改变了变量x的值 。 在开始时, x包含的值是100。但在调用该函数后,其值变成了748,如输出中所示。

// Go program to create a pointer
// and passing it to the function
package main
  
import "fmt"
  
// taking a function with integer
// type pointer as an parameter
func ptf(a *int) {
  
    // dereferencing
    *a = 748
}
  
// Main function
func main() {
  
    // taking a normal variable
    var x = 100
  
        fmt.Printf("The value of x before function call is: %d\n", x)
  
    // taking a pointer variable
    // and assigning the address
    // of x to it
    var pa *int = &x
  
    // calling the function by
    // passing pointer to function
    ptf(pa)
  
    fmt.Printf("The value of x after function call is: %d\n", x)
  
}

输出

The value of x before function call is: 100
The value of x after function call is: 748

将变量的地址传递给函数调用

考虑到下面的程序,我们没有创建一个指针来存储变量x的地址,即像上面程序中的pa 一样。我们直接将 x 的地址传递给函数调用,这与上面讨论的方法一样。

// Go program to create a pointer
// and passing the address of the
// variable to the function
package main
  
import "fmt"
  
// taking a function with integer
// type pointer as an parameter
func ptf(a *int) {
  
    // dereferencing
    *a = 748
}
  
// Main function
func main() {
  
    // taking a normal variable
    var x = 100
      
    fmt.Printf("The value of x before function call is: %d\n", x)
  
    // calling the function by
    // passing the address of
    // the variable x
    ptf(&x)
  
    fmt.Printf("The value of x after function call is: %d\n", x)
  
}

输出

The value of x before function call is: 100
The value of x after function call is: 748

注意: 你也可以使用简短的声明操作符(:=)来声明上述程序中的变量和指针。