go - 我可以在一个函数上使用两个 for 循环还是有更好的方法?

标签 go

我正在写一个家庭作业问题,我可能过度设计了太多的结构。这在当时是有道理的。我想遍历季节性折扣(通过 2 个不同的数组 - HighPrices 和 LowPrices),只是不确定 a) 设置是否良好,b) 如何以较少冗余的方式添加价格。

package main

import (
    "fmt"
    "time"
)

func main() {
    fmt.Println(getPrice(2, "bananas"))
}

func getPrice(p float32, f string) float32 {

    type HighPriceItems struct {
        items []string
        price float32
    }
    type LowPriceItems struct {
        items []string
        price float32
    }
    type seasonMatrix struct {
        h HighPriceItems
        l LowPriceItems
    }
    var seasonPrices = func() seasonMatrix {
        var h = HighPriceItems{}
        var l = LowPriceItems{}

        var season = seasonMatrix{}

        switch time.Now().Month() {

        case time.March, time.April, time.May, time.June, time.July:

            h := append(h.items, "apples", "oranges", "pears")
            l := append(l.items, "bananas", "grapes")
            season.h.items = h
            season.h.price = 4
            season.l.items = l
            season.l.price = 2
            return season
        case time.August, time.September, time.October, time.November, time.December, time.January, time.February:

            h := append(h.items, "bananas", "grapes")
            l := append(l.items, "apples", "oranges", "pears")
            season.h.items = h
            season.h.price = 4
            season.l.price = 2
            season.l.items = l
            return season
        }
        return season
    }

    const normalDiscount float32 = .75

    var x = p * normalDiscount
    var specials = seasonPrices()
    var finalPrice float32

    for _, n := range specials.h.items {

        if f == n {
            if specials.h.price > x {
                finalPrice = specials.h.price

            } else {
                finalPrice = x
            }
        }
    }
    for _, n := range specials.l.items {
        if f == n {
            if specials.l.price > x {
                finalPrice = specials.l.price
            } else {
                finalPrice = x
            }
        }
    }
    return finalPrice
}

最佳答案

没有理由使用 HighPriceItemLowPriceItem 类型。

如果您将其设为单个 PriceItems,您将能够将末尾的 2 个 for 循环转换为 PriceItems 上的函数并删除重复项第二个 for 循环中的代码。

同样在 Go 中 var specials = seasonPrices() 通常写成 specials := seasonPrices()

关于go - 我可以在一个函数上使用两个 for 循环还是有更好的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55437404/

相关文章:

javascript - 如何从 HTML 中的嵌入式 Javascript 中抓取值?

go - 使用超时运行命令并在 go 中一次读取一行标准输出

ssl - tls : oversized record received with length XXXXX

go - `go install` 、 `govendor install +local` 和 `govendor install +vendor,^program` 有什么区别?

math - 如何在屏幕坐标上使用三角函数来计算点之间的角度

facebook - 使用huandu/facebook Golang FB api时出现DecodeField错误

go - Golang毒蛇,我无法在MergeConfigMap之后获得字段

image - Golang 为 jpeg 图像生成一致的哈希值,而无需写入磁盘

GO:使用错误的参数运行 cli 命令

go - 为什么json值是空的