- 新增 funcTypes1.go 文件,使用匿名函数实现计算器逻辑 - 修改 main.go 调用新增的 main1 和 main2 函数- 初始化 structs 模块的 go.mod 文件 - 恢复 structs/main.go 原始内容并保留调试提示注释
31 lines
636 B
Go
31 lines
636 B
Go
package main
|
|
|
|
import "fmt"
|
|
|
|
func printPrice2(product string, price float64, calculator calcFunc) {
|
|
fmt.Println("Product:", product, "Price:", calculator(price))
|
|
}
|
|
|
|
func selectCalculator2(price float64) calcFunc {
|
|
if price > 100 {
|
|
var withTax calcFunc = func(price float64) float64 {
|
|
return price + (price * 0.2)
|
|
}
|
|
return withTax
|
|
}
|
|
var withoutTax calcFunc = func(price float64) float64 {
|
|
return price
|
|
}
|
|
return withoutTax
|
|
}
|
|
|
|
func main2() {
|
|
products := map[string]float64{
|
|
"Kayak": 275,
|
|
"LifeJacket": 48.95,
|
|
}
|
|
for product, price := range products {
|
|
printPrice2(product, price, selectCalculator2(price))
|
|
}
|
|
}
|