Ad space (banner)
๐ŸนGo Lessons
Lesson 15 / 68

Anonymous Functions (Closures)

In this lesson you will learn to write anonymous functions (closures) in Go so you can handle one-off logic flexibly. This is for anyone searching for "Go anonymous functions closures how to use".

Go has no ternary operator (writing it out with an if statement is the idiomatic style). Instead you use an anonymous function, created on the spot without a name. You can assign it to a variable or call it immediately.

The sample code assigns an anonymous function to the variable double with double := func(n int) int { return n * 2 }, then calls it as double(5) just like a normal function. An anonymous function can also act as a "closure", remembering the variables around it.

A common stumbling block for beginners is the syntax itself. The idea of writing func(params) returnType { body } and assigning it to a variable on the spot can feel awkward when you are used to ordinary function declarations.

In real-world development anonymous functions are also the usual body of a goroutine, making them a frequent sight in Go's concurrent programming.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Go directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)