Home > Article > Backend Development > Application scenarios of function pointers and closures in Golang
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 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
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
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!