【发布时间】:2020-07-14 14:57:24
【问题描述】:
我知道我们不能在 Go 中使用 struct 作为常量。 但我想将我的常量分组以获得更简洁的代码,而不是有许多带有一些前缀的常量,所以我这样做:
var SomeStatus = struct {
Active int
Inactive int
Others int
}{
Active: 1,
Inactive: 2,
Others: 3
}
// usage example
status = Status.Active
// example with some prefix
const StatusActive = 1
const StatusInactive = 2
const StatusOthers = 3
const OtherConstantVariable = 1
...
如果没关系,变量的值可以改写。 这个技巧的另一个副作用是什么?
【问题讨论】:
-
对性能有轻微影响,因为它是分配内存而不是常量。
标签: go memory struct constants