IIFE (Immediately Invoked Function Expression)
Immediately Invoking Anonymous Functions
UsageUsed with
deferto 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
deferinside 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.
- Ensuring lock safety: guaranteeing that the Lock is released via
e.g.1func() { 2 s.startedLock.Lock() 3 defer s.startedLock.Unlock() // This anonymous function will unlock immediately when it finishes. 4 // ... 5}() - By declaring
-
deferinside loops- ⚠️ Because
deferis executed when the function returns, it is not executed immediately within a loop. - Create an anonymous function (IIFE) and declare
deferalong with the logic inside it.
- ⚠️ Because