In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)05/31 Report--
This article introduces the knowledge of "how to use Go callback functions and closures". Many people will encounter this dilemma in the operation of actual cases, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
Go callback functions and closures
When a function has the following two characteristics, it can be called a higher-order function (high order functions):
A function can be used as an argument to another function (typically a callback function)
A function can return another function, that is, another function as the return value of this function (typical use is closure)
In general, it comes with another feature: a function can be assigned to a variable as a value.
F: = func () {...} f ()
Because functions in Go cannot nest named functions, functions can only return anonymous functions when they are returned.
First briefly introduce the higher-order function, and then introduce the closure.
Examples of higher-order functions
For example, use a function as an argument to another function:
Package mainimport "fmt" func added (msg string, a func (a, b int) int) {fmt.Println (msg, ":", a (33, 44))} func main () {/ / the named function / / can only be defined in main (): = func (a) B int) int {return aqb} added ("aquib", f)}
The following example is that a function returns another function:
Package mainimport "fmt" func added () func (a, b int) int {f: = func (a, b int) int {return a + b} return f} func main () {m: = added () fmt.Println (m (33, 44))} callback function (sort.SliceStable)
Taking function B as the parameter of another function A can make function A more universal, and function B can be defined at will. As long as it meets the rules, function A can deal with it, which is more suitable for callback function.
In Go's sort package, there is a powerful Slice sorting tool, SliceStable (), which takes the sort function as a parameter:
Func SliceStable (slice interface {}, less func (I, j int) bool)
What does this function mean? Given a Slice structure named slice, use a function named less to sort the slice. The structure of this less function is less func (I, j int) bool, where I and j specify the sort by. The sorting algorithm has been built into Go. We do not need to define the sorting algorithm ourselves. Go will automatically fetch the corresponding elements of I and j indexes from Slice, and then call back the sorting function less. So we just need to pass ascending or descending order and sort by what sort.
For example:
Package mainimport ("fmt"sort") func main () {S1: = [] int {112,22,52,32,12} / / define the sorting function less: = func (I, j int) bool {/ / descending sort return S1 [I] > S1 [j] / ascending sort: S1 [I]
< s1[j] } // sort.SliceStable(s1, less) fmt.Println(s1)} 这里的排序函数就是回调函数。每取一次i和j对应的元素,就调用一次less函数。 可以将排序函数直接写在SliceStable()的参数位置: sort.SliceStable(s1, func(i, j int) bool { return s1[i] >S1 [j]})
It can also be stronger and more flexible. For example, compare in character size order rather than numeric size:
Package mainimport ("fmt"sort"strconv") func main () {S1: = [] int {112,220,52,32,42} sort.SliceStable (S1, func (I, j int) bool {/ / convert the element values corresponding to I and j into the string bi: = strconv.FormatInt (int64 (S1 [I])) 10) bj: = strconv.FormatInt (int64 (S1 [j]), 10) / / sort return bi > bj} in descending character order) fmt.Println (S1)}
Compare by string length:
Package mainimport ("fmt"sort") func main () {S1: = [] string {"hello", "malong", "gaoxiao"} sort.SliceStable (S1, func (I, j int) bool {/ / sort return len (S1 [I] > len (S1 [j]}) fmt.Println (S1)} in descending byte size order
More strictly, it is compared by bytes, because len () gets the number of bytes rather than characters when manipulating the string. If you want to compare by number of characters, use the following code:
Package mainimport ("fmt"sort") func main () {S1: = [] string {"hello", "gaoxiao"} sort.SliceStable (S1, func (I) J int) bool {/ / sort return len ([] rune (S1 [I]) > len ([] rune (S1 [j])}) fmt.Println (S1)} closure in descending order by byte size
Function A returns function B. the most typical use is closure.
To put it simply, a closure is a special function composed of "one function + one scope environment". This function can access a variable that is not internal to itself, that is, the variable is in another scope, and the variable is not assigned, but is waiting for us to assign.
For example:
Package mainimport "fmt" func f (x int) func (int) int {g: = func (y int) int {return x closure} / / return closure return g} func main () {/ / assign the return result of the function "closure" to the variable a: = f (3) / / call the closure function res: = a (5) fmt stored in the variable. Println (res) / / you can call closures directly / / because closures are not assigned to variables So it is called anonymous closure fmt.Println (f (3) (5))}
The g returned by f () above is called a closure function because it is a function and references a variable x that is not within its own scope, which is a variable in the scope of g, because x is an unknown, unassigned free variable.
If x is assigned before it is passed to g, then the closure function should not be called a closure, because such a closure is meaningless.
The following g is also a closure function, but this closure function is custom, not obtained from the function return function.
Package mainimport "fmt" func main () {/ / Free variable x var x int / / closure function g g: = func (I int) int {return x + I} x = 5 / / call closure function fmt.Println (g (5)) x = 10 / / call Closure function fmt.Println (g (3))}
The reason why g is also a closure function is that it accesses a variable x that does not belong to itself, and this variable is unbound when the closure function is defined, that is, a free variable.
The role of the closure is obvious. In the first closure example, after f (3) exits, the closure function g () it returns still remembers the xdistinct 3 that originally belonged to f (). This allows many closure functions to share the value of the same free variable x.
For example, the following a (3), a (5), a (8) all share xroom3 from f ().
A: = f (3) a (3) a (5) a (8)
Looking at the function of the outer layer, f (3) can bind the free variable x to xroom3, and naturally it can also bind to xroom5, xroom8, and so on.
So, when do you use closures? In general, closures are appropriate when the process can be divided into two or more parts that are factory-oriented (in fact, in some places closures are directly called factory functions). The first part is that you can bind different values to free variables in batches, and the second part is that multiple closure functions can share the free variables after the first step binding.
That's all for "how to use Go callback functions and closures". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.