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 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号