Home  >  Article  >  Backend Development  >  Application scenarios of function pointers and closures in Golang

Application scenarios of function pointers and closures in Golang

王林
王林Original
2024-04-15 18:18:021163browse

Function pointers are used in Go for function callbacks, deferred execution, and polymorphism. Closures are used for state management, event handling, and lazy initialization.

Application scenarios of function pointers and closures in Golang

Application scenarios of function pointers and closures in Go

Function pointers

Function pointer is a variable pointing to a function. Function pointer types can be declared using the func keyword:

type Fn func(int) int

Function pointers can be passed as parameters to other functions:

func apply(fn Fn, arg int) int {
    return fn(arg)
}

Closure

A closure is a function that references variables in the scope of an external function. Closures can be created by defining nested functions within functions:

func counter() func() int {
    i := 0
    return func() int {
        i++
        return i
    }
}

Application scenarios

Function pointers

  • For function callbacks: pass a function as a parameter and call it at some time in the future.
  • Delayed execution: Store the function pointer in a variable and execute it when needed.
  • Polymorphism: Polymorphism can be achieved by passing different function pointers to the same function.

Practical case: Sorting using function pointers

type Person struct {
    Name string
    Age  int
}

type ByName []Person

func (a ByName) Len() int           { return len(a) }
func (a ByName) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a ByName) Less(i, j int) bool { return a[i].Name < a[j].Name }

type ByAge []Person

func (a ByAge) Len() int           { return len(a) }
func (a ByAge) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a ByAge) Less(i, j int) bool { return a[i].Age < a[j].Age }

func main() {
    people := []Person{
        {Name: "Alice", Age: 30},
        {Name: "Bob", Age: 25},
        {Name: "Charlie", Age: 35},
    }

    sort.Sort(ByName(people))
    fmt.Println(people) // [{Name: Alice Age: 30} {Name: Bob Age: 25} {Name: Charlie Age: 35}]

    sort.Sort(ByAge(people))
    fmt.Println(people) // [{Name: Bob Age: 25} {Name: Alice Age: 30} {Name: Charlie Age: 35}]
}

In this case, the function pointers ByName and ByAge Specifies different sorting criteria for Person slices.

Closure

  • For state management: Closures can save variables in the function scope even if the function has returned.
  • Event handling: Closures can be used to create functions that respond to specific events.
  • Lazy initialization: Closures can be used to delay initializing variables until they are needed.

Practical case: Using closure to implement counter

func main() {
    getCount := counter()

    fmt.Println(getCount()) // 1
    fmt.Println(getCount()) // 2
    fmt.Println(getCount()) // 3
}

In this case, closuregetCount saves the internal counter variablei, and returns the incremented value on each call.

The above is the detailed content of Application scenarios of function pointers and closures in Golang. 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