dplbf4340 2016-03-29 15:39
浏览 252
已采纳

在GO中自定义类型的ENUM

I am trying to generate an enum for a type I defined

type FeeStage int

From this I learned that I can use iota to create an enum based on this type

const(
     Stage1 FeeStage = iota
     Stage2 
     Stage3
)

However, manipulating the actual values of the enum is rather cumbersome and error prone

const(
     Stage1 FeeStage = iota           // 0
     Stage2          = iota + 6       // 7
     Stage3          = (iota - 3) * 5 // -5
)

Is there a way to automatically convert a list of ENUMs with custom values to a certain type. This is what I was using before but only converts the first member of the constant to the custom type.

const(
     Stage1 FeeStage = 1
     Stage2          = 2
     Stage3          = 2
)

Here is a playground with a similar result

  • 写回答

3条回答 默认 最新

  • douquan1953 2016-03-29 15:48
    关注

    There's no way beyond either using iota and automatic enums, or doing the most straightforward thing:

    const(
         Stage1 FeeStage = 1
         Stage2 FeeStage = 2
    
         // or another syntax with same results
         Stage3 = FeeStage(2)
    )
    

    which IMHO is less cumbersome than doing stuff like iota + 5 which as you said is really bad.

    I usually either use iota if the value is not important beyond the context of the program, or explicit typing if I need the values to be used in a protocol or something.

    Though I have to say sometimes just using ints or strings is good enough, it depends on the context. See for example the http status codes in the standard library. They don't have a special type.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥50 易语言把MYSQL数据库中的数据添加至组合框
  • ¥20 求数据集和代码#有偿答复
  • ¥15 关于下拉菜单选项关联的问题
  • ¥20 java-OJ-健康体检
  • ¥15 rs485的上拉下拉,不会对a-b<-200mv有影响吗,就是接受时,对判断逻辑0有影响吗
  • ¥15 使用phpstudy在云服务器上搭建个人网站
  • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
  • ¥15 vue3+express部署到nginx
  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况