English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
GoProgramming language or a pointer in Golang is a variable used to store anothervariablethe memory address ofArrayis a fixed-length sequence used to store elements of the same type in memory.
You can use a pointer to an array and pass it as a parameter to the function. To understand this concept, let's take an example. In the following program, we will use an array containing5a pointer array of elementsarr. We need to use the function to update this array. This means modifying the array inside the function (the array here is.78{89{45{56{14},()), and it will reflect at the caller. Therefore, here we adoptupdatearrayfunction, which has a pointer to the array as the parameter type. Usingupdatearray(&arr)*(40 Or funarr[ 75The code, we passed the address of the array. Inside the function (40 Or funarr[ 75] =78 89 45 56 750 The code uses dereferencing to assign a new value to the array, which will reflect in the original array. Finally, the program will output [
// 0]. //Golang program passes a pointer to Use a slice as a function parameter package main //Array as a function parameter Define a function *[5func updatearray(funarr // )int) { Use the index value to change the array*(4] = 750 //funarr)[ //You can also write // funarr[4] = 750 } func main() { //The above code line Get the pointer to the array5int{78, 89, 45, 56, 14} //arr := [ //Pass the pointer to the array And execute updatearray //updatearray(&arr) Updated array }
Output:
[78 89 45 56 750]
fmt.Println(arr)Note:
// Example //Golang program to illustrate Use a slice as a function parameter package main import "fmt" //func updateslice(funarr []int) { //Update the value at the specified index funarr[4] = 750 } func main() { //Define a slice s := [5int{78, 89, 45, 56, 14} //Pass the slice to //Function updateslice updateslice(s[:]) //Display the result fmt.Println(s) }
Output:
[78 89 45 56 750]