Pattern) IIFE

IIFE (Immediately Invoked Function Expression)

Immediately Invoking Anonymous Functions

Usage

Used with defer to control the release timing of resources (e.g., Locks, files, timers).

  • To avoid affecting subsequent logic (e.g., email sending, file uploads),
    forcing the clean-up of prior operations to occur sooner.
  • When a Lock is required in the initialization logic within a function

    • By declaring defer inside an anonymous function, it is called when the anonymous function's execution (e.g., initialization logic) finishes.
      • Ensuring lock safety: guaranteeing that the Lock is released via defer.
    e.g.
    1func() {
    2	s.startedLock.Lock()
    3	defer s.startedLock.Unlock() // This anonymous function will unlock immediately when it finishes.
    4	// ...
    5}()
    
  • defer inside loops

    • ⚠️ Because defer is executed when the function returns, it is not executed immediately within a loop.
    • Create an anonymous function (IIFE) and declare defer along with the logic inside it.

Post
Category
Series