dongqin1861 2016-05-28 06:48
浏览 56

如何在golang中检查值是否为iota常数类型?

I have a following type defined using iota in golang.

type StatusType int

const (
    PENDING StatusType = iota
    APPROVED
    REJECTED
)

I want to restrict the value passed in in REST-API to the StatusType. Such that the value should not exceed 0,1,2.

  • 写回答

7条回答 默认 最新

  • dongtanzhu5417 2016-05-28 07:10
    关注

    Simply don't export StatusType (assuming you define it in package 'status').
    This follow "What is an idiomatic way of representing enums in Go?":

    type statusType int
    
    const (
        PENDING statusType = iota
        APPROVED
        REJECTED
    )
    type StatusTyper interface {
        StatusType() statusType 
    }
    
    func(st statusType) StatusType() statusType {
        return st
    }
    

    Any external package would then refer to StatusType-like variable as status.PENDING, status.APPROVED or status.REJECTED.
    (the only three statusType which implement the StatusTyper interface. Caveat applies.)

    评论

报告相同问题?