Files
bulma/function_type.go

73 lines
1.4 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package main
import "fmt"
// 定义函数类型(计算函数)
type Calculator func(int, int) int
// 实现加法
func add(a, b int) int {
return a + b
}
// 实现乘法
func multiply(a, b int) int {
return a * b
}
// 函数作为参数(策略模式)
func calculate(a, b int, op Calculator) int {
return op(a, b)
}
// 高阶函数:返回函数
func apply(f func(int) int, x int) int {
return f(x)
}
// 闭包:捕获外部变量
func makeAdder(base int) Calculator {
// 匿名函数捕获base
return func(a, b int) int {
return a + b + base
}
}
// 闭包:计数器
func counter() func() int {
count := 0
return func() int {
count++
return count
}
}
func main() {
// 函数作为变量
var calc Calculator = add
fmt.Println("3+5=", calc(3, 5)) // 8
// 函数作为参数
fmt.Println("2*4=", calculate(2, 4, multiply)) // 8
// 高阶函数调用
double := func(x int) int { return x * 2 }
fmt.Printf("apply(4, double)=%d\n", apply(double, 4)) // 输出8
// 闭包示例
adder := makeAdder(10) // 基础值10
fmt.Println("1+2+10=", adder(1, 2)) // 13
// 计数器闭包
c1 := counter()
fmt.Printf("c1第1次: %d\n", c1()) // 输出1
fmt.Printf("c1第2次: %d\n", c1()) // 输出2
c2 := counter()
fmt.Printf("c2第1次: %d\n", c2()) // 输出1c1与c2的count独立)
// 错误示例
// var f func()
// f() // 报错:panic: runtime error: invalid memory address or nil pointer dereference
}