parameters - Go 如何查看产品类型

标签 parameters go


我有带有字段 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/

相关文章:

javascript - ExtJs4 - 存储 baseParams 配置属性?

api - 我可以在我的 Go 程序中直接使用 go-ipfs 吗?

datetime - Go:获取两个时间之间的差异时出错

indexing - 戈朗 : int to slice conversion

c++ - 将子类传递给采用其父类(super class)的函数

ios - Swift 函数参数默认值

matlab - 如何求解具有 transient 参数的常微分方程组

function - LISP:以谓词作为参数

go - 在 Cadence 工作流程中的循环内调用相同的事件

go - 在 Go 中使用嵌入式类型的基