猿问

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方式做到这一点?


DIEA
浏览 182回答 2
2回答

慕仙森

真正最简单的是使用映射,不像常量那么快,但是如果您必须针对大集合进行测试,这是最方便的方法。此外,由于它是预先分配的,因此它是线程安全的,因此您不必担心锁定,除非您在运行时添加它。var (    ptTypes = map[string]struct{}{        "ProductRT": {},        "ProductDT": {},        "ProductEX": {},        "ProductTK": {},        "ProductQT": {},        "ProductGD": {},    })func validType(t string) (ok bool) {    _, ok = ptTypes[t]    return}
随时随地看视频慕课网APP

相关分类

Go
我要回答