Home  >  Article  >  Backend Development  >  The principles and applications of golang function pointers

The principles and applications of golang function pointers

PHPz
PHPzOriginal
2024-04-29 11:15:01881browse

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.

The principles and applications of golang function pointers

Principles and applications of function pointers in Go language

Principles of function pointers

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

Creating a function pointer

Function pointers can be created in the following ways:

  1. Direct assignment:

    var add = func(a, b int) int {
        return a + b
    }
    var addPtr = &add
  2. Use func Keyword:

    var addPtr = func(a, b int) int {
        return a + b
    }

Calling a function pointer

To call a function pointer, you need to use the () operator, as shown below:

result := (*addPtr)(1, 2)  // 等于 add(1, 2)

Actual case:

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn