什么是枚举?
枚举(enumeration)的缩写,是一种特殊的数据类型,表示一组命名值。它用于定义概念上相关的常量值的集合,提高代码可读性并减少由于使用任意文字值而导致的错误。
// Enum in Java enum TrafficLight { RED, YELLOW, GREEN }
# Enum in Python from enum import Enum class TrafficLight(Enum): RED = 1 GREEN = 2 BLUE = 3
Go 中的枚举
Go 本身不支持枚举。然而,在 Go 中定义枚举的流行方法是使用 iota 方法。
package main type TrafficLight int const ( RED TrafficLight = iota // 0 GREEN // 1 BLUE // 2 ) func main() { fmt.Println(RED) // Output: 0 }
但是,以这种方式处理枚举时存在一些问题:
- 缺乏内置方法:不直接支持列出所有枚举值或在字符串和枚举之间转换等功能。
- 有限类型安全:枚举通常使用基本类型(例如 int 或 string)表示,这会增加意外分配的风险。
- 序列化和反序列化复杂性:将枚举映射到 JSON 等格式或从 JSON 等格式映射需要额外的处理。
xybor-x/enum 库
xybor-x/enum 库为 Go 枚举提供了优雅、易于使用且功能强大的解决方案,无需生成代码。
有一些类型的枚举可以与 xybor-x/enum 一起使用,请选择最合适的一种。
基本枚举
优点?
- 简单。
- 支持常量值。
缺点?
- 没有内置方法。
- 没有类型安全。
- 缺乏序列化和反序列化支持。 与传统枚举一样,基本枚举没有内置方法。但是您可以使用 xybor-x/enum 的实用函数来处理这种类型的枚举。
package main type Role int const ( RoleUser Role = iota RoleAdmin ) func init() { enum.Map(RoleUser, "user") enum.Map(RoleAdmin, "admin") // Optional: ensure no new enum values can be added to Role. enum.Finalize[Role]() } func main() { // Print the corresponding string. fmt.Println(enum.ToString(RoleUser)) // Output: user // Print out all valid enums. fmt.Println(enum.All[Role]()) // Output: [0 1] // Parse an enum from int. r1, ok := enum.FromInt[Role](1) fmt.Println(ok) // Output: true fmt.Println(enum.ToString(r1)) // Output: admin // Parse an enum from string. r2, ok := enum.FromString[Role]("admin") fmt.Println(ok) // Output: true fmt.Println(r2) // Output: 1 // Serialize json. data, err := enum.MarshalJSON(RoleUser) fmt.Println(err) // Output: nil fmt.Println(string(data)) // Output: "user" }
包裹枚举
优点?
- 支持常量值。
- 提供了许多有用的内置方法。
- 开箱即用的完整序列化和反序列化支持。
缺点?
- 仅提供基本类型安全。
package main // Only need to change the two following lines fromthe Basic enum. type role any type Role = enum.WrapEnum[role] const ( RoleUser Role = iota RoleAdmin ) func init() { enum.Map(RoleUser, "user") enum.Map(RoleAdmin, "admin") // Optional: ensure no new enum values can be added to Role. enum.Finalize[Role]() } func main() { // Print the corresponding string. No need to use enum.ToString. fmt.Println(RoleUser) // Output: user // Print out all valid enums. fmt.Println(enum.All[Role]()) // Output: [user admin] // Parse an enum from int. r1, ok := enum.FromInt[Role](1) fmt.Println(ok) // Output: true fmt.Println(r1) // Output: admin // Parse an enum from string. r2, ok := enum.FromString[Role]("admin") fmt.Println(ok) // Output: true fmt.Println(r2) // Output: admin // Now you can use json.Marshal instead of enum.MarshalJSON. data, err := json.Marshal(RoleUser) fmt.Println(err) // Output: nil fmt.Println(string(data)) // Output: "user" }
WrapEnum 是最适合一般情况的枚举。然而,它只提供基本的类型安全。如果您想要更严格的,请考虑使用 SafeEnum。
// WrapEnum cannot prevent this type of invalid declaration. // Consider using SafeEnum. r := Role(42)
安全枚举
SafeEnum 定义了一个强类型安全枚举。与 WrapEnum 一样,它提供了一组内置方法来简化枚举的使用。
SafeEnum 强制执行严格的类型安全,确保只允许预定义的枚举值。它可以防止意外创建新的枚举类型,从而提供一组有保证的有效值。
优点?
- 提供强大的类型安全性。
- 提供了许多有用的内置方法。
- 开箱即用的完整序列化和反序列化支持。
缺点?
- 不支持常量值。
为什么持续支持很重要?
一些静态分析工具(例如 bazel 的 nogo、具有详尽扩展的 golangci-lint)支持检查常量枚举中的详尽 switch 语句。通过选择具有持续支持的枚举,您可以在这些工具中启用此功能。
// Enum in Java enum TrafficLight { RED, YELLOW, GREEN }
参考
xybor-x/enum:https://github.com/xybor-x/enum
中:https://medium.com/@huykingsofm/enum-handling-in-go-a2727154435e
越南语 viblo:https://viblo.asia/p/cac-van-de-cua-go-enum-va-cach-giai-quyet-voi-xybor-xenum-Yym401A9J91
以上是Go Enum 与 xybor-x/enum 的问题及解决方案的详细内容。更多信息请关注PHP中文网其他相关文章!

Go的"strings"包提供了丰富的功能,使字符串操作高效且简单。1)使用strings.Contains()检查子串。2)strings.Split()可用于解析数据,但需谨慎使用以避免性能问题。3)strings.Join()适用于格式化字符串,但对小数据集,循环使用 =更有效。4)对于大字符串,使用strings.Builder构建字符串更高效。

Go语言使用"strings"包进行字符串操作。1)拼接字符串使用strings.Join函数。2)查找子串使用strings.Contains函数。3)替换字符串使用strings.Replace函数,这些函数高效且易用,适用于各种字符串处理任务。

资助bytespackageingoisesential foreffited byteSemanipulation,uperingFunctionsLikeContains,index,andReplaceForsearchingangingAndModifyingBinaryData.itenHancesperformanceNandCoderAceAnibility,MakeitiTavitalToolToolToolToolToolToolToolToolToolForhandLingBinaryData,networkProtocols,networkProtocoLss,networkProtocols,andetFilei

Go语言使用"encoding/binary"包进行二进制编码与解码。1)该包提供binary.Write和binary.Read函数,用于数据的写入和读取。2)需要注意选择正确的字节序(如BigEndian或LittleEndian)。3)数据对齐和错误处理也是关键,确保数据的正确性和性能。

1)usebybytes.joinforconcatenatinges,2)bytes.bufferforincrementalWriter,3)bytes.indexorbytes.indexorbytes.indexbyteforsearching bytes.bytes.readereforrednerncretinging.isnchunk.ss.ind.inc.softes.4)

theencoding/binarypackageingoiseforporptimizingBinaryBinaryOperationsDuetoitssupportforendiannessessandefficityDatahandling.toenhancePerformance:1)usebinary.nativeendiandiandiandiandiandiandiandian nessideendian toavoid avoidByteByteswapping.2)

Go的bytes包主要用于高效处理字节切片。1)使用bytes.Buffer可以高效进行字符串拼接,避免不必要的内存分配。2)bytes.Equal函数用于快速比较字节切片。3)bytes.Index、bytes.Split和bytes.ReplaceAll函数可用于搜索和操作字节切片,但需注意性能问题。

字节包提供了多种功能来高效处理字节切片。1)使用bytes.Contains检查字节序列。2)用bytes.Split分割字节切片。3)通过bytes.Replace替换字节序列。4)用bytes.Join连接多个字节切片。5)利用bytes.Buffer构建数据。6)结合bytes.Map进行错误处理和数据验证。


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

Dreamweaver Mac版
视觉化网页开发工具

适用于 Eclipse 的 SAP NetWeaver 服务器适配器
将Eclipse与SAP NetWeaver应用服务器集成。

SublimeText3汉化版
中文版,非常好用

螳螂BT
Mantis是一个易于部署的基于Web的缺陷跟踪工具,用于帮助产品缺陷跟踪。它需要PHP、MySQL和一个Web服务器。请查看我们的演示和托管服务。

DVWA
Damn Vulnerable Web App (DVWA) 是一个PHP/MySQL的Web应用程序,非常容易受到攻击。它的主要目标是成为安全专业人员在合法环境中测试自己的技能和工具的辅助工具,帮助Web开发人员更好地理解保护Web应用程序的过程,并帮助教师/学生在课堂环境中教授/学习Web应用程序安全。DVWA的目标是通过简单直接的界面练习一些最常见的Web漏洞,难度各不相同。请注意,该软件中