Go 中的常量全局用户类型值



我想安排计算一个初始化后不会改变的值。

我会使用 const,但 Go 将 consts 限制为内置类型,IIUC。

所以我想我会使用 var ,并在 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
}

这很好 - 但是有没有办法在计算后"锁定"值,而不是将变量更改为未导出的名称,然后使用函数访问器返回其值?

不,没有。 变量之所以这样称呼,是因为它们的值可以更改。在 Go 中没有"final"或类似的修饰符。语言的简单性。

防止变量从外部更改的唯一方法是使其未导出,是的,然后您需要导出函数来获取它们的值。

解决方法可能是不使用变量而是使用常量。是的,你不能有结构常量,但如果结构很小,你可以将其字段用作单独的常量,例如:

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

作为一个选项,你可以移动这些"常量">

func init() {
    screenBounds := types.RectFromPointSize(
        types.Pt(-ScreenWidth/2, 0),
        types.Pt(ScreenWidth, ScreenHeight))
    BoardBounds := ScreenBounds
    BoardBounds.Max.Y += TankSpeed * TotalFrames
}

到一个单独的包中,并将它们定义为不可导出,并定义一个可导出的函数,如下所示:

func GetScreenBounds() types.SomeType {
 return screenBounds
}

这是一些开销,但它将使您能够安全地使用该常量。

最新更新