gpt4 book ai didi

nim-lang - Nim 中的字符串枚举类型?

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

是否可以为字符串定义类似枚举的类型?我知道枚举,但在这种情况下不想使用枚举,我想使用它就好像它只是一个字符串一样。

type Blog = object
text: string
priority: "low" | "normal" | "high"

echo Blog(text: "something...", priority: "high")

最佳答案

枚举可以附加一个字符串值。转换器可用于将字符串自动解析为枚举。示例( playground ):

import strutils  # for parseEnum

type
Priority = enum
pLow = "low", pNormal = "normal", pHigh = "high"
Blog = object
text: string
priority: Priority

converter toPriority(s: string): Priority = parseEnum[Priority](s)

echo Blog(text: "something...", priority: "high")
#note that parseEnum is style insensitive
echo Blog(text: "something...", priority: "LOW")
try:
echo Blog(text: "something...", priority: "medium")
except:
echo getCurrentExceptionMsg()
输出:
(text: "something...", priority: high)
(text: "something...", priority: low)
invalid enum value: medium
类型定义和转换器可能会在宏中自动化,例如:
stringEnum:
Priority = ["low", "medium", high"]
宏的实现留给读者作为练习:)

关于nim-lang - Nim 中的字符串枚举类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63931540/

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