Golang 指向数组的指针作为函数参数
Go编程语言或Golang中的指针是一个变量,用来存储另一个变量的内存地址。而数组是一个固定长度的序列,用来存储内存中的同质元素。
你可以使用指向数组的指针,并将其作为一个参数传递给函数。为了理解这个概念,让我们举一个例子。在下面的程序中,我们正在使用一个有5个元素的指针数组 arr 。我们想用一个函数来更新这个数组。意味着在函数中修改数组(这里的数组是{78, 89, 45, 56, 14}),这将反映在调用者身上。所以在这里我们使用了函数 updatearray ,它的参数类型是指向数组的指针。使用 **updatearray( &arr) **这行代码,我们传递的是数组的地址。在函数(*funarr)[4]=750或funarr[4]=750中,这一行代码使用了取消引用的概念,将新的值分配给数组,这将反映在原始数组中。最后,该程序将给出输出 [78 89 45 56 750] 。
// Golang program to pass a pointer to an
// array as an argument to the function
package main
import "fmt"
// taking a function
func updatearray(funarr *[5]int) {
// updating the array value
// at specified index
(*funarr)[4] = 750
// you can also write
// the above line of code
// funarr[4] = 750
}
// Main Function
func main() {
// Taking an pointer to an array
arr := [5]int{78, 89, 45, 56, 14}
// passing pointer to an array
// to function updatearray
updatearray(&arr)
// array after updating
fmt.Println(arr)
}
输出
[78 89 45 56 750]
注意: 在Golang中,我们不建议使用数组的指针作为函数的参数,因为代码会变得难以阅读。而且,这也不是实现这一概念的好方法。为了达到这个目的,你可以使用slice来代替传递指针。
例子
// Golang program to illustrate the
// concept of passing a pointer to an
// array as an argument to the function
// using a slice
package main
import "fmt"
// taking a function
func updateslice(funarr []int) {
// updating the value
// at specified index
funarr[4] = 750
}
// Main Function
func main() {
// Taking an slice
s := [5]int{78, 89, 45, 56, 14}
// passing slice to the
// function updateslice
updateslice(s[:])
// displaying the result
fmt.Println(s)
}
输出
[78 89 45 56 750]
极客教程