English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
GoUn puntatore in un linguaggio di programmazione o in Golang è una variabile che viene utilizzata per memorizzare un altrovariabileindirizzo di memoria. EarrayIt is 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 a pointer array containing 5 elementsarr. We need to use the function to update this array. This means modifying the array internally (in this case, the array is{78, 89, 45, 56, 14}), and it will reflect at the caller's location. Therefore, here we useupdatearrayA function that has a pointer to an array as the parameter type. Usingupdatearray(&arr)The code (*funarr)[4] = 750 or funarr[4] = 750 uses dereferencing to assign a new value to the array, which will be reflected in the original array. Finally, the program will output [78 89 45 56 750].
//The Golang program passes the address of the array //Array as a function parameter package main import "fmt" //Define a function func updatearray(funarr *[5]int) { //Use the index value to change the array (*funarr)[4] = 750 //You can also write //The above code line //funarr[4] = 750 } func main() { //Get the pointer to the array arr := [5]int{78, 89, 45, 56, 14} //Pass the pointer to the array //And execute updatearray updatearray(&arr) //The updated array fmt.Println(arr) }
Output:
[78 89 45 56 750]
Note:In Golang, it is not recommended to use a pointer to an array as a function parameter because the code becomes difficult to read. Similarly, it is not a good method to implement this function. For this purpose, you can use a slice instead of passing a pointer.
//To explain the Golang program //Use the slice as a function parameter package main import "fmt" func updateslice(funarr []int) { //Update the value //Update the value at the specified index funarr[4] = 750 } func main() { //Define a slice s := [5]int{78, 89, 45, 56, 14} //Pass the slice to //Function updateslice updateslice(s[:]) //Show the result fmt.Println(s) }
Output:
[78 89 45 56 750]