我有带有字段 Type
的模型 Product
。
像这样:
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
方式执行此操作?
最佳答案
与其对基本类型使用类型别名,不如对私有(private) 类型使用类型别名(这意味着您无法在包外初始化的结构)
参见 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
部分中定义的公共(public)值之外的任何其他值。
如果您设法将值传递给 printProductType(pt ProductType
),则您的值始终是有效值。
对于动态检查部分,即OneOfOne地址 in his answer ,我会添加一个函数 GetProductType(name string) ProductType
其中:
- 检查名称是否有效
- 返回上面 var 部分中定义的官方
ProductType
实例之一。
这样,您的其余代码将始终使用官方 ProductType 值(而不是使用恰好与正确值匹配的“字符串”)
关于parameters - Go 如何查看产品类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27250086/