Home >Backend Development >Golang >The principles and applications of golang function pointers
Function pointers in Go allow functions to be stored as values. Creation methods include direct assignment and use of the func keyword. Called via the () operator. Practical application example: Calculate the sum of odd elements in an array, and pass the odd number judgment function through a function pointer.
In the Go language, a function is a value that can Use variables to store. A function pointer is a variable that points to a function. It is represented by the *
prefix, and the syntax is as follows:
type FuncType func(args) (returns) var funcPtr *FuncType
Function pointers can be created in the following ways:
Direct assignment:
var add = func(a, b int) int { return a + b } var addPtr = &add
Use func
Keyword:
var addPtr = func(a, b int) int { return a + b }
To call a function pointer, you need to use the ()
operator, as shown below:
result := (*addPtr)(1, 2) // 等于 add(1, 2)
Calculate the sum of odd elements in the array
package main import "fmt" // 奇数函数 func isOdd(x int) bool { return x%2 != 0 } // 计算奇数和 func sumOdds(arr []int, odd func(int) bool) int { sum := 0 for _, v := range arr { if odd(v) { sum += v } } return sum } func main() { arr := []int{1, 2, 3, 4, 5, 6, 7} total := sumOdds(arr, isOdd) fmt.Println("奇数元素的和:", total) }
Output:
奇数元素的和: 16
The above is the detailed content of The principles and applications of golang function pointers. For more information, please follow other related articles on the PHP Chinese website!