

Anonymous functions and closures
source link: https://yourbasic.org/golang/anonymous-function-literal-lambda-closure/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Anonymous functions and closures
A function literal (or lambda) is a function without a name.

In this example a function literal is passed as the less
argument to the sort.Slice
function.
func Slice(slice interface{}, less func(i, j int) bool)
people := []string{"Alice", "Bob", "Dave"}
sort.Slice(people, func(i, j int) bool {
return len(people[i]) < len(people[j])
})
fmt.Println(people)
// Output: [Bob Dave Alice]
You can also use an intermediate variable.
people := []string{"Alice", "Bob", "Dave"}
less := func(i, j int) bool {
return len(people[i]) < len(people[j])
}
sort.Slice(people, less)
Note that the less
function is a closure: it references the people
variable, which is declared outside the function.
Closures
Function literals in Go are closures: they may refer to variables defined in an enclosing function. Such variables
- are shared between the surrounding function and the function literal,
- survive as long as they are accessible.
In this example, the function literal uses the local variable n
from the enclosing scope to count the number of times it has been invoked.
// New returns a function Count.
// Count prints the number of times it has been invoked.
func New() (Count func()) {
n := 0
return func() {
n++
fmt.Println(n)
}
}
func main() {
f1, f2 := New(), New()
f1() // 1
f2() // 1 (different n)
f1() // 2
f2() // 2
}
Share:
Recommend
-
10
Closures, Anonymous Classes and an alternative approach to Test Mocking (Part 4) ...
-
13
Closures, Anonymous Classes and an alternative approach to Test Mocking (Part 3) ...
-
4
Closures, Anonymous Classes and an alternative approach to Test Mocking (Part 2) ...
-
10
Closures, Anonymous Classes and an alternative approach to Test Mocking (Part 1) Since their first introduction with...
-
5
21 January 2016 / Mozilla Closures and first-class functions I wrote a long and probably dull chapter on closures and first-c...
-
9
Closures: Magic Functions Jan 17, 2019 If you want to respond to this post, please respond via Rust users or
-
8
Reading Time: 2 minutes In this blog, we will go through the concepts of higher order functions and closures in Scala with the help of example. 1. Higher Order Functions A higher order function takes other functions as...
-
9
0:00 / 1:06:39 ...
-
9
Hello Everyone, In this post we will explore the HOF (Higher order function), Callbacks, and the crazy JavaScript Closures which made us all pull our hairs at some point in our learning journey. Higher Order Function
-
7
Closures and Anonymous Functions in Go Search ...
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK