String Enum Type in Nim?

Viewed 783

Is it possible to define enum-like type for string? I know about enums but don't want to use enums in this case, I want to use it as if it's just a string.

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

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

Enums can have a string value attached to it. A converter could be used for automatic parsing of string to enum. Example (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()

output:

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

type definition and converter could probably be automated in a macro such as:

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

Implementation of macro left as an exercise for the reader :)

Related