douman6245 2017-02-02 19:58
浏览 91
已采纳

在Go中枚举常量的最佳方法

I'm starting to learn Go after other languages. Go has a very elegant way of creating constants with numeric values like:

const (
    _      = iota    // 0 and is skipped
    Sunday           // 1
    Monday           // 2
    ...
)

This is very easy to write, but is it really easy to maintain? For example, if you suddenly insert new value to between present, all subsequent will change their values. And it will be hard to find, only scrupulous diff reading can reveal it. Or errors on other parts. How can I extract these values with names and use in other parts of a program, or in database? For example for PostgreSQL I can define:

CREATE TYPE color AS ENUM ('', 'Sunday', 'Monday');

Just to illustrate an idea. For example, Python has Enum type:

from enum import Enum
class Color(Enum):
    RED = 1
    GREEN = 2
    BLUE = 3

Then you may use it like Color.RED. Next I can take all values:

list(Color)
[<Color.RED: 1>, <Color.BLUE: 2>, <Color.GREEN: 3>]

This allows me to "introspect" to module and create easily-readable enums in databases. For example for PostgreSQL I can define:

CREATE TYPE color AS ENUM ('RED', 'GREEN', 'BLUE');

How can I:

  1. Reflect golang constants names?
  2. Make error-proof constants which cannot drift their values? Only fix them manually?
  3. May be there's an idiomatic way to do it better?

Thanks.

  • 写回答

3条回答 默认 最新

  • doulang5323 2017-02-02 20:02
    关注

    1) You can use stringer to generate the names https://godoc.org/golang.org/x/tools/cmd/stringer

    2) Not sure what you mean? Most languages will allow you to drift values, you should always add to the end of the list if you want the number to stay constant, or like in python you could explicitly set each value to a number instead of using iota.

    3) Not really, enums just aren't great in golang

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

报告相同问题?

悬赏问题

  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3