问题是Nim语言的具体情况。 我正在寻找一种标准,以一种类型安全的方式将整数/字符串转换为枚举。使用ord()和$()可以很容易地从enum转换为整数/字符串,但是我无法轻松地进行相反的转换。
假设我有以下类型声明
ProductGroup {.pure.} = enum
Food = (3, "Food and drinks"),
kitchen = (9, "Kitchen appliance and cutlery"),
Bedroom = (15, "Pillows, Beddings and stuff"),
Bathroom = (17, "Shower gels and shampoo")
我正在寻找一种标准的方法:
const
product1 : seq[ProductGroup] = xxSomethingxx(@[3, 3, 17, 9, 15])
product2 : seq[ProductGroup] = zzSomethingzz(@["Kitchen appliance and cutlery", "Kitchen appliance and cutlery", "Shower gels and shampoo"])
product3 : seq[ProductGroup] = xxSomethingxx(@[2]) ## compilation error "2 does not convert into ProductGroup"
答案 0 :(得分:4)
从int到enum的类型转换,从string到enum的strutils.parseEnum:
import strutils, sequtils
type ProductGroup {.pure.} = enum
Food = (3, "Food and drinks"),
kitchen = (9, "Kitchen appliance and cutlery"),
Bedroom = (15, "Pillows, Beddings and stuff"),
Bathroom = (17, "Shower gels and shampoo")
const
product1 = [3, 3, 17, 9, 15].mapIt(ProductGroup(it))
product2 = ["Kitchen appliance and cutlery", "Kitchen appliance and cutlery", "Shower gels and shampoo"].mapIt(parseEnum[ProductGroup](it))
product3 = ProductGroup(2)