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

时间:2019-05-30 14:22:00

标签: go static const init idiomatic

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

我会使用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
}

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

2 个答案:

答案 0 :(得分:5)

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

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

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

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

答案 1 :(得分:1)

您可以选择移动这些“常量”

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

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

放入一个单独的程序包中,并将其定义为 unexportable ,并定义一个 exportable 函数,如下所示:

func GetScreenBounds() types.SomeType {
 return screenBounds
}

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