gpt4 book ai didi

enums - Nim : standard way to convert integer/string to enum

转载 作者:行者123 更新时间:2023-12-01 12:22:26 25 4
gpt4 key购买 nike

问题是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")

我正在寻找一种标准的方法:
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"

最佳答案

从int到enum的类型转换,从字符串到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)

关于enums - Nim : standard way to convert integer/string to enum,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42977509/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com