GOLANG“Namespaced”枚举? [英] GOLANG "Namespaced" enums?
问题描述
type topicStatus int
我知道在GO中创建枚举的惯用方法如下:
const(
注册topicStatus = iota
活动
不活动
等待移除
移除
)
但是如果我有另一个想要重复使用名称的enum,我得到一个错误:
类型hotelVisit int
常量(
注册hotelVisit = iota
检入
checked- out
)
在这里,如果我尝试这个,我无法区分topicStatus.registered和hotelVisit.registered as registeredregisteredwas used used - there's a way tonamespacetheenumnames?
使用许多可能导致命名冲突的常见词小写标识符来污染命名空间并不是我认为习惯使用的Go。
我可能会这样做:
type topicStatus int
const(
ts注册topicStatus = iota
tsActive
tsInactive
tsPendingRemoval
tsRemoved
)
类型hotelVisit int
const(
hvRegistered hotelVisit = iota
hvCheckedIn
hvCheckedOut
)
现在您可以声明并初始化为 ts:= tsPendingRemoval
。清晰简洁,命名冲突的风险很小。
I understand that the idiomatic way to create an enum in GO is as follows:
type topicStatus int
const (
registered topicStatus = iota
active
inactive
pending-removal
removed
)
but if I have another "enum" that wants to "reuse" a name, I get an error:
type hotelVisit int
const (
registered hotelVisit = iota
checked-in
checked-out
)
Here, if I try this, I cannot differentiate between topicStatus.registered and hotelVisit.registered as "registered" was previously used - is there a way to "namespace" the "enum" names?
Polluting the namespace with numerous common word lower case identifiers that are likely to cause naming conflicts isn't something I'd consider idiomatic Go. Same goes for creating packages just to hold a handful of constant declarations.
I'd probably do something like this:
type topicStatus int
const (
tsRegistered topicStatus = iota
tsActive
tsInactive
tsPendingRemoval
tsRemoved
)
type hotelVisit int
const (
hvRegistered hotelVisit = iota
hvCheckedIn
hvCheckedOut
)
Now you can declare and initialize with ts := tsPendingRemoval
. Clear and concise with little risk of naming conflicts.
这篇关于GOLANG“Namespaced”枚举?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!