DEV Community

Huseyn
Huseyn

Posted on

Anonymous functions, Factory functions, and Closures in Go

πŸ”§ Real-Life Scenario: Online Order Discount System
You are building a Go backend for an e-commerce platform. Different users (like guests, regulars, and VIPs) get different discounts on their orders. We want a flexible way to calculate the discount based on user type.

Let’s incorporate:

Anonymous Function – A function without a name, used right away.

Factory Function – A function that returns another function based on input (creates logic on-the-fly).

Closure – When the returned function remembers variables from its surrounding scope.

GO CODE (With comments)

package main

import "fmt"

// Factory Function: Returns a discount function based on user type
func DiscountFactory(userType string) func(total float64) float64 {
    var baseDiscount float64

    // Set base discount rate depending on user type
    switch userType {
    case "guest":
        baseDiscount = 0.0
    case "regular":
        baseDiscount = 0.05
    case "vip":
        baseDiscount = 0.10
    }

    // Closure: This anonymous function captures baseDiscount
    return func(total float64) float64 {
        return total - (total * baseDiscount)
    }
}

func main() {
    // Create discount calculators
    guestDiscount := DiscountFactory("guest")
    regularDiscount := DiscountFactory("regular")
    vipDiscount := DiscountFactory("vip")

    totalAmount := 1000.0

    fmt.Println("Original Total:", totalAmount)

    // Using closures returned from factory function
    fmt.Println("Guest Pays:", guestDiscount(totalAmount))     // 1000.0
    fmt.Println("Regular Pays:", regularDiscount(totalAmount)) // 950.0
    fmt.Println("VIP Pays:", vipDiscount(totalAmount))         // 900.0

    // Anonymous function used inline (e.g., flash sale)
    flashSale := func(amount float64) float64 {
        return amount * 0.8 // 20% off
    }

    fmt.Println("Flash Sale Price:", flashSale(totalAmount))   // 800.0
}

Enter fullscreen mode Exit fullscreen mode

Breakdown of Concepts

Concept Explanation
Anonymous Function flashSale := func(amount float64) float64 {...} – This function has no name and is defined inline.
Factory Function DiscountFactory(userType string) – Returns a custom discount function based on input.
Closure Each returned function captures the baseDiscount variable from its creation environment – it remembers it even after DiscountFactory has finished running.

Why This Is Useful in Real Life
This kind of setup allows:

  • πŸ’‘ Dynamic behavior – Discounts are customized based on user types without duplicating code.
  • πŸ” Encapsulation – Each closure hides its internal logic (like baseDiscount).
  • πŸ” Reusability – The factory function can be reused for any user type or even expanded with more logic.

Top comments (0)