๐ Class 21 โ Expressions, Anonymous Functions & IIFE in Go
๐ฅ Video Name:
Anonymous function, Expression & IIFE
๐ฆ Code Written in This Class
// Anonymous function
// IIFE - Immediately Invoked Function Expression
package main
import "fmt"
func main() {
// Anonymous function
func(a int, b int) {
c := a + b
fmt.Println(c)
}(5, 7) // IIFE
}
func init() {
fmt.Println("I'll be called first")
}
๐ง Key Concepts
๐งฎ Expression in Go
An expression is any snippet of code that evaluates to a value.
Examples:
a + b // is an expression
func(x, y){} // is a function expression
Expressions can be used as values, passed around, or even executed immediately โ which leads us toโฆ
๐ง Anonymous Function
An anonymous function is a function without a name.
Instead of:
func add(a, b int) int {
return a + b
}
You write:
func(a, b int) int {
return a + b
}
โ You can assign it to a variable, pass it as an argument, or invoke it on the spot.
โก IIFE (Immediately Invoked Function Expression)
An IIFE is an anonymous function that is executed immediately right after it's defined.
Syntax:
func(a int, b int) {
// do stuff
}(5, 7)
Use-case: You want to run a small block of logic immediately, without polluting the namespace with a new function name.
๐ฅ๏ธ CLI-style Execution Visualization
=========== Compilation Phase =============
Found init() โ
Found main() โ
=========== Execution Phase ===============
๐ init() runs first
โ Prints: I'll be called first
๐ง Data Segment:
(No global vars in this case)
๐ Stack Frame:
โโโโโโโโโโโโโโโโโโโโโโโ
โ main() โ
โ โโโโโโโโโโโโโโโโโโโ โ
โ โ anonymous func โ โ
โ โโโโโโโโโโโโโโโโโโโ โ
โโโโโโโโโโโโโโโโโโโโโโโ
main() calls an IIFE:
โ Passes 5 and 7
โ Inside IIFE: c := 5 + 7 = 12
โ Prints: 12
=========== Execution Complete =============
๐งต TL;DR
-[] โ Expressions return values and can be assigned or executed.
-[] ๐งช Anonymous functions have no name, great for quick logic blocks.
-[] ๐ IIFE: Define & execute in one go. Great for one-off logic.