类型化常量声明列表
我希望创建一个具有以下属性的“类似枚举”的常量列表:
- 每个标识符的值都是连续的,有一些间隙。 (我相信 iota 和空白标识符在这方面有所帮助)。
- 标识符是模块私有的。
- 这些常量只能与同类型的其他常量进行比较。
枚举基于 枚举fuse_opcode
来自FUSE 。这是我想要完成的一些代码(也是非常错误的):
const Opcode (
_ = iota // skip 0
lookupOp
forgetOp
getattrOp
setattrOp
readlinkOp
symlinkOp // 6
_ // skip 7
mknodOp // 8
// et cetera ad nauseam
)
I wish to create an "enum-like" list of constants with the following properties:
- The values of each identifier are sequential, with a few gaps. (I believe iota and the blank identifier help in this regard).
- The identifiers are private to the module.
- The constants can only be compared with other constants of the same type.
The enumeration is based on the enum fuse_opcode
from FUSE. Here's some code for what I'm trying to accomplish (and also very wrong):
const Opcode (
_ = iota // skip 0
lookupOp
forgetOp
getattrOp
setattrOp
readlinkOp
symlinkOp // 6
_ // skip 7
mknodOp // 8
// et cetera ad nauseam
)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你想要这样的东西。您仍然可以将这些常量与文字整数进行比较(无法阻止这种情况),但与其他整数值的任何比较或赋值都会出现编译器错误。
如果您确实想阻止外部包看到这些是整数常量的事实,但您仍然希望它们具有可比性,您可以考虑执行类似的操作,
并且仅在 API 中公开 OpCode。我还建议明确记录它的可比性。
You want something like this. You can still compare these constants against literal integers (there's no way to prevent that) but any comparison or assignment to other integer values will get a compiler error.
If you really want to prevent external packages from seeing the fact that these are integer constants, but you still want it comparable, you might consider doing something like this,
and only exposing OpCode in your API. I'd also suggest explicitly documenting that it's comparable.
这是 FUSE 操作码的 Go 代码。它是从 枚举fuse_opcode。通常,您会编写一个脚本来执行此操作;我使用了文本编辑器。由于常量值与 C 枚举值匹配,因此使用显式值。
Here's the Go code for the FUSE opcodes. It was created from enum fuse_opcode. Typically you would write a script to do that; I used a text editor. Since the constant values match the C enum values, explicit values are used.