Anonymous Functions and Closures Golang Tutorial 03 — Code Thursday

kerstan
Towards Dev
Published in
4 min readFeb 15, 2024

Subscribed to: https://medium.com/@kerstan

Hi guys, I am Kerstan. Today is Code Thursday.

I will share you about Anonymous Functions and Closures in Golang.

So, let’s get started.

Image generated with PaintingForYou

1. Anonymous Function

Go language supports anonymous functions, implying that functions can be passed around or utilized like ordinary variables. Anonymous functions can be assigned to variables, serving as fields within structures.

Anonymous functions have the capability to directly access external variables.

package main

import "fmt"

func main() {
// 1
var v func(a int) int
// Anonymous function, that is, there is no function name
v = func(a int) int {
return a * a
}
fmt.Println(v(6))

// 2
fn := func() {
fmt.Println("Hello World")
}
// The calling of anonymous function
fn()
}

2. Closures

The Go language supports anonymous functions, enabling the creation of closures. An anonymous function acts as an “inline” statement or expression. One of the strengths of anonymous functions is their ability to directly use the variables inside the function, without the need for…

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Bug Bounty Hunter | Programming