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