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?
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
)
As an option you can move these "constants"
func init() {
screenBounds := types.RectFromPointSize(
types.Pt(-ScreenWidth/2, 0),
types.Pt(ScreenWidth, ScreenHeight))
BoardBounds := ScreenBounds
BoardBounds.Max.Y += TankSpeed * TotalFrames
}
into a separate package and define them as unexportable and also define an exportable function like this:
func GetScreenBounds() types.SomeType {
return screenBounds
}
It's some overhead but it will provide you ability to use that constants securely.