Why is this code giving an error at runtime?
import std/[strutils]
type LineChar = enum
Space = '.'
Start = 'S'
Splitter = '^'
Beam = '|'
case parseEnum[LineChar](".")
of Space:
echo "Space"
else:
discard
I have this error:
/usercode/in.nim(10) in
/playground/nim/lib/std/enumutils.nim(77) parseEnum
Error: unhandled exception: Invalid enum value: . [ValueError]
I expect echo "Space".
The chars are used as ordinal values for the enum fields, not for their string representation. To get what you want, use:
import std/[strutils]
type LineChar = enum
Space = ('.', ".")
Start = ('S', "S")
Splitter = ('^', "^")
Beam = ('|', "|")
case parseEnum[LineChar](".")
of Space:
echo "Space"
else:
discardNim enumerations have 2 internal values:
Ordinal value defaults to 0 and increases by 1 with each item. But you can change it by assigning any ordinal value to enum values:
type Foo = enum
A = 1
B = 2
C
echo Foo(1) # prints "A"
echo parseEnum[Foo]("A") # prints "A"
echo Foo.A.int # prints "1"
echo Foo.B.int # prints "2"
echo Foo.C.int # prints "3"
Ordinal value can be changed using value of any ordinal type, not just integers (int, uint, char, byte, other enum) Note: if your ordinal values are not consecutive, it's a holed enum and some operations won't work with it (e.g. inc, dec, succ, pred and indexing arrays)
type Buzz = enum
A = '.' # ascii 46
B = ':' # ascii 58 (should be 47 or '/' for non-holed enum)
echo Buzz('.') # prints "A"
echo Buzz(46) # prints "A"
echo parseEnum[Buzz]("A") # prints "A"
echo Buzz.A.int # prints "46"
echo Buzz.B.int # prints "58"
String value is what used in parsing and for string conversions. It defaults to the name of identifier: You can change it by assigning a different string value:
type Bar = enum
A = "first"
B = "second"
C
echo Bar(0) # prints "first"
echo parseEnum[Bar]("first") # prints "first"
echo parseEnum[Bar]("C") # prints "C"
echo Bar.C # prints "C"
And finally, you can change both ordinal and string values at the same time:
type Quux = enum
A = ('.', "first")
B = (':', "second")
C = ('_', "third")
echo Quux('.') # prints "first"
echo parseEnum[Quux]("first") # prints "first"
echo Quux.A # prints "first"
echo Quux.A.int # prints "46"
Playground Version: https://play.nim-lang.org/#pasty=HgyubQbk