π§ 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
}
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)