Nim:将 integer/string 转换为枚举的标准方法
Nim: standard way to convert integer/string to enum
问题是特定于 Nim 语言的。
我正在寻找一种以类型安全的方式将 integer/string 转换为枚举的标准。使用 ord() 和 $() 从枚举转换为 integer/string 很容易,但我找不到一种简单的方法来进行相反的转换。
假设我有以下类型声明
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"
从整型到枚举的类型转换,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)
问题是特定于 Nim 语言的。 我正在寻找一种以类型安全的方式将 integer/string 转换为枚举的标准。使用 ord() 和 $() 从枚举转换为 integer/string 很容易,但我找不到一种简单的方法来进行相反的转换。
假设我有以下类型声明
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"
从整型到枚举的类型转换,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)