转到如何检查产品类型

时间:2014-12-02 13:00:01

标签: parameters go


我的模型Product包含字段Type
像这样:

type ProductType string

var (
    PtRouteTransportation    ProductType = "ProductRT"
    PtOnDemandTransportation ProductType = "ProductDT"
    PtExcursion              ProductType = "ProductEX"
    PtTicket                 ProductType = "ProductTK"
    PtQuote                  ProductType = "ProductQT"
    PtGood                   ProductType = "ProductGD"
)

type Product struct {
    ...
    Type ProductType
    ...
}

Create函数中,我有type形式参数:

type := req.Form.Get("type")


问题:如何检查type是否有效?

最简单的方法是:

if type != PtRouteTransportation && type != PtOnDemandTransportation && ...

但如果Product有100种类型,我该怎么做?

如何以go方式执行此操作?

2 个答案:

答案 0 :(得分:4)

为什么不使用私有类型的类型别名(意味着你无法在包外面初始化的结构),而不是使用基本类型的类型别名

请参阅this example

type ProductType productType

type productType struct {
    name string
}

var (
    PtRouteTransportation    ProductType = ProductType(productType{"ProductRT"})
    PtOnDemandTransportation ProductType = ProductType(productType{"ProductDT"})
    PtExcursion              ProductType = ProductType(productType{"ProductEX"})
    PtTicket                 ProductType = ProductType(productType{"ProductTK"})
    PtQuote                  ProductType = ProductType(productType{"ProductQT"})
    PtGood                   ProductType = ProductType(productType{"ProductGD"})
)

func printProductType(pt ProductType) {
    fmt.Println(pt.name)
}
func main() {
    fmt.Println("Hello, playground")
    // printProductType("test") // cannot use "test" (type string) as type ProductType in argument to printProductType
    printProductType(PtRouteTransportation)
}

这意味着您无法使用除var部分中定义的公共值以外的任何其他值。

如果您设法将值传递给printProductType(pt ProductType),则您的值始终是有效值。


对于动态检查部分,OneOfOne地址in his answer,我会添加一个函数GetProductType(name string) ProductType,其中:

  • 检查名称是否有效
  • 返回上面var部分中定义的官方ProductType个实例之一。

这样,代码的其余部分始终使用官方的ProductType值(而不是使用'字符串'恰好匹配正确的值)

答案 1 :(得分:3)

真正最简单的方法是使用地图,而不是像常量一样快,但如果你必须对大型集进行测试,那么这是最方便的方法。

此外,由于它是预分配的,因此它是线程安全的,因此您不必担心锁定,除非您在运行时添加它。

var (
    ptTypes = map[string]struct{}{
        "ProductRT": {},
        "ProductDT": {},
        "ProductEX": {},
        "ProductTK": {},
        "ProductQT": {},
        "ProductGD": {},
    }

)

func validType(t string) (ok bool) {
    _, ok = ptTypes[t]
    return
}