2014-12-02 1 views
1


Type 필드의 모델 Product가 있습니다. 이 같은
뭔가 : 나는 type 폼 PARAM이Go 제품의 종류를 확인하는 방법

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 := req.Form.Get("type") 


질문 : 확인하는 방법 type이 유효합니까?

가장 간단한 방법은 다음과 같습니다

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

하지만 Product 100 종류를 사용할 경우에 어떻게해야 무엇?

go 방법은? 대신 왜 개인 유형으로 유형 별칭을 사용하지 않는, 기본 유형으로 유형 별칭을 사용

+0

'유형'의 유형은 무엇입니까? – Franchu

답변

3

정말 간단한지도를 사용하는 것입니다 (오른쪽 값과 일치하는 일어나는 '문자열'로가 아닌) 공식 ProductType 값으로 작동 , 상수만큼 빠르지는 않지만 큰 세트에 대해 테스트해야한다면 가장 편리한 방법입니다.

또한 미리 할당되었으므로 스레드로부터 안전하므로 런타임에 추가하지 않는 한 잠금에 대해 걱정할 필요가 없습니다.

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

) 

func validType(t string) (ok bool) { 
    _, ok = ptTypes[t] 
    return 
} 
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를 추가하는 동적 검사의 경우


, 어떤 : 이름은 유효 하나 개
  • 수익률은 공식 ProductType 인스턴스 중 하나입니다

    • 확인하는 경우 위의 var 섹션에 정의되어 있습니다.

    그런 식으로, 코드의 나머지 부분은 항상

  • +0

    그건 확인하는데 도움이 안된다. – OneOfOne

    +0

    @OneOfOne 왜? 어떻게 다른 것을 전달할 수 있니? – VonC

    +0

    그는'req.Form.Get ("type")'이 유효한 타입인지 확인하려고하는데, 문자열을 무언가와 대조해야합니다. – OneOfOne

    관련 문제