问题是特定于 Nim 语言的。我正在寻找一种以类型安全的方式将整数/字符串转换为枚举的标准。使用 ord() 和 $() 很容易从枚举转换为整数/字符串,但我找不到一种简单的方法来进行相反的转换。
假设我有以下类型声明
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")
Run Code Online (Sandbox Code Playgroud)
我正在寻找一种标准的方法:
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"
Run Code Online (Sandbox Code Playgroud)
从 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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1804 次 |
| 最近记录: |