dqwh26750 2019-05-30 14:22
浏览 60

Go中恒定的全局用户类型值

I want to arrange to compute a value that will not change after initialization.

I'd use const, but Go restricts consts to built-in types, IIUC.

So I figured I'd use var, and compute their initial values in init()

var (
    // ScreenBounds is the visible screen
    ScreenBounds types.Rectangle

    // BoardBounds is the total board space
    BoardBounds  types.Rectangle
)

func init() {
    ScreenBounds := types.RectFromPointSize(
        types.Pt(-ScreenWidth/2, 0),
        types.Pt(ScreenWidth, ScreenHeight))

    BoardBounds := ScreenBounds
    BoardBounds.Max.Y += TankSpeed * TotalFrames
}

Which is pretty good - but is there a way to "lock" the values once computed, other than to change the vars to unexported names, and then uses function-accessors to return their values?

  • 写回答

2条回答 默认 最新

  • dongpiao1983 2019-05-30 14:25
    关注

    No, there is not. Variables are called that because their values can be changed. In Go there is no "final" or similar modifier. Simplicity of the language.

    Only way to guard a variable from being changed from the outside is to make it unexported, and yes, then you need exported functions to get their values.

    A workaround could be to not use variables but constants. Yes, you can't have struct constants, but if the structs are small, you may use its fields as separate constants, e.g.:

    const (
        ScreenMinX = ScreenWidth / 2
        ScreenMinY = ScreenHeight / 2
        ScreenMaxX = ScreenWidth
        ScreenMaxY = ScreenHeight
    )
    
    评论

报告相同问题?

悬赏问题

  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作