亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Go 如何檢查產品類型

Go 如何檢查產品類型

Go
DIEA 2021-09-09 15:05:15
我有Product帶字段的模型Type。像這樣的東西:type ProductType stringvar (    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 回答

?
慕仙森

TA貢獻1827條經驗 獲得超8個贊

真正最簡單的是使用映射,不像常量那么快,但是如果您必須針對大集合進行測試,這是最方便的方法。


此外,由于它是預先分配的,因此它是線程安全的,因此您不必擔心鎖定,除非您在運行時添加它。


var (

    ptTypes = map[string]struct{}{

        "ProductRT": {},

        "ProductDT": {},

        "ProductEX": {},

        "ProductTK": {},

        "ProductQT": {},

        "ProductGD": {},

    }


)


func validType(t string) (ok bool) {

    _, ok = ptTypes[t]

    return

}


查看完整回答
反對 回復 2021-09-09
  • 2 回答
  • 0 關注
  • 199 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號