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

Mor*_*hai 1 static const idiomatic init go

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

我会使用const,但是Go将const限制为内置类型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
}
Run Code Online (Sandbox Code Playgroud)

哪一个非常好-但是除了将vars更改为未导出的名称,然后使用函数访问器返回其值之外,是否有一种方法可以“锁定”计算后的值?

icz*_*cza 5

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

防止变量从外部被更改的唯一方法是不导出变量,是的,那么您需要导出的函数来获取它们的值。

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

const (
    ScreenMinX = ScreenWidth / 2
    ScreenMinY = ScreenHeight / 2
    ScreenMaxX = ScreenWidth
    ScreenMaxY = ScreenHeight
)
Run Code Online (Sandbox Code Playgroud)