Nim 中的字符串枚举类型?

String Enum Type in Nim?

是否可以为字符串定义类似枚举的类型?我知道枚举,但不想在这种情况下使用枚举,我想将它当作一个字符串来使用。

type Blog = object
  text:     string
  priority: "low" | "normal" | "high"

echo Blog(text: "something...", priority: "high")

枚举可以附加一个字符串值。转换器可用于将字符串自动解析为枚举。示例 (playground):

import strutils  # for parseEnum

type
  Priority = enum
    pLow = "low", pNormal = "normal", pHigh = "high"
  Blog = object
    text:     string
    priority: Priority

converter toPriority(s: string): Priority = parseEnum[Priority](s)

echo Blog(text: "something...", priority: "high")
#note that parseEnum is style insensitive
echo Blog(text: "something...", priority: "LOW")
try:
  echo Blog(text: "something...", priority: "medium")
except:
  echo getCurrentExceptionMsg()

输出:

(text: "something...", priority: high)
(text: "something...", priority: low)
invalid enum value: medium

类型定义和转换器可能会在宏中自动执行,例如:

stringEnum:
  Priority = ["low", "medium", high"]

宏的实现留作 reader :)

的练习