English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Golang Basic Tutorial

Golang Control Statements

Golang Function & Method

Golang Struct

Golang Slice & Array

Golang String(String)

Golang Pointer

Golang Interface

Golang Concurrency

Golang Exception(Error)

Golang Other Miscellaneous

Go Language Pointer as Function Parameter

Go programming languageThe pointer in the variable is a variable used to store the memory address of another variable. You can also likeVariableLike passing a pointer to the function. There are two ways to perform the following operation:

  • Create a pointer and pass it to the function

  • Pass the memory address of the variable

Create a pointer and pass it to the function

In the following program, we use the functionptf, the function has an integer type pointer parameter, indicating that the function only accepts pointer type parameters. At the same time, this function changes the variablex. At the beginning,xContains the value100. But after the function call, the value changes to748, as shown in the output.

// Go program creates a pointer
//and pass it to the function
package main
import "fmt"
//Accept pointers as parameters
func ptf(a *int) {
    //Dereference
    *a = 748
}
func main() {
    //Normal variable
    var x = 100
    fmt.Printf("The value of x before the function call is: %d\n", x)
    //Get a pointer variable
    //and allocate the address
    var pa *int = &x
    //Call the function in the following way
    //Pass the pointer to the function
    ptf(pa)
    fmt.Printf("The value of x after the function call is: %d\n", x)
}

Output:

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

Pass the address of the variable to the function call

Consider the following program, where we did not create a pointer to store the variablexThe address, which is the address in the above program,pa. We directly passxPass the address to the function call, which is similar to the method above.

package main
import "fmt"
// int type pointer as parameter
func ptf(a *int) {
    *a = 748
}
func main() {
    var x = 100
    fmt.Printf("The value of x before the function call is: %d\n", x)
    //By calling the function
    //Pass the address
    //Variable x
    ptf(&x)
    fmt.Printf("The value of x after the function call is: %d\n", x)
}

Output:

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

Note:You can also use the short declaration operator (:=) to declare variables and pointers in the above program.