【问题标题】:What are the side effects of using structs to group constants使用结构对常量进行分组的副作用是什么
【发布时间】: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


【解决方案1】:

这个技巧的另一个副作用是什么?

我能想到的。可能还有其他人:

  • 效率较低,因为变量分配运行时内存。
  • 由于常量而可能在编译时预先计算的任何值现在都将在运行时计算。
  • 对于导出的符号,任何导入您的包的人都可以在运行时对其进行修改。
  • 这不是惯用的,因此可能会使任何看到您的代码的人感到困惑。
  • 失去了来自无类型常量的灵活性。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-15
    • 2010-12-21
    • 1970-01-01
    • 1970-01-01
    • 2021-07-28
    • 1970-01-01
    • 2010-11-07
    • 1970-01-01
    相关资源
    最近更新 更多