๐Ÿ“˜ 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.