duanluangua8850 2015-04-16 03:29
浏览 225
已采纳

检查枚举中是否存在值

I have created a strict like the following in my app:

type Datatype int8

const (
    user Datatype = iota
    address
    test
)

var datatypes = [...]string{"User", "Address", "Test"}

func (datatype Datatype) String() string {
    return datatypes[datatype]
}

I would like to be able to validate a value passed via a command-line flag against this enum.

I thought I had seen something like dtype == Datatype being used, but I am apparently sorely mistaken.

If this is not possible I can go the route of putting these values in an array. However, I feel the enum approach is more elegant.

  • 写回答

1条回答 默认 最新

  • dpj83664 2015-04-16 04:43
    关注

    From your code sample it looks like you are trying to see if a map (rather than a struct) contains a particular key.

    If so, the answer is here

    A two-value assignment tests for the existence of a key:

    i, ok := m["route"] 
    

    In this statement, the first value (i) is assigned the value stored under the key "route". If that key doesn't exist, i is the value type's zero value (0). The second value (ok) is a bool that is true if the key exists in the map, and false if not.

    To test for a key without retrieving the value, use an underscore in place of the first value:

    _, ok := m["route"]
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 sim800c模块 at指令及平台
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题