Golang闭包使用场景

保存中间态

package main

import "fmt"

// 保存中间态
func increment() func() int {
    count := 0
    return func() int {
       count++
       return count
    }
}
func main() {
    inc := increment()
    fmt.Println(inc())
    fmt.Println(inc())
    fmt.Println(inc())
    fmt.Println(inc())
}

工厂模式

package main

import "fmt"

func CalcFactory(operation string) func(int, int) int {
	switch operation {
	case "add":
		return func(a, b int) int {
			return a + b
		}
	case "subtract":
		return func(a, b int) int {
			return a - b
		}
	case "multiply":
		return func(a, b int) int {
			return a * b
		}
	case "divide": // 这里是向下取整了,因为函数签名返回是int
		return func(a, b int) int {
			if b != 0 {
				return a / b
			}
			return 0
		}
	default:
		return nil
	}
}

func main() {
	addFunc := CalcFactory("add")
	subtractFunc := CalcFactory("subtract")
	multiplyFunc := CalcFactory("multiply")
	divideFunc := CalcFactory("divide")

	fmt.Println(addFunc(4, 5)) //9
	fmt.Println(subtractFunc(4, 5)) // -1
	fmt.Println(multiplyFunc(4, 5))// 20
	fmt.Println(divideFunc(5, 4))// 1
}


image-20250130234346284

装饰器模式

package main

import "fmt"

func doubleAndPrint(fn func(int) int) func(int) int {
	return func(i int) int {
		result := fn(i)
		fmt.Println(result)
		return result
	}
}

func square(x int) int {
	return x * x
}

func main() {
	doubleSquare := doubleAndPrint(square)
	doubleSquare(2)
}

image-20250130234635377