Constant Blocks and Untyped Constants
const blocks
You can group related constants together in a single block:
const (
namaGame = "Petualangan Nusantara"
levelMaksimum = 50
nyawaAwal = 3
)
Untyped constants
A constant like const pajak = 0.11 doesn't have a "locked-in" type yet. Go only decides its type when the constant is used. That's why a single constant can work with different number types without any conversion:
const bonus = 5
var a int = 10 + bonus // bonus diperlakukan sebagai int
var b float64 = 2.5 + bonus // bonus diperlakukan sebagai float64
Here bonus is treated as an int in the first line and as a float64 in the second. Compare that with a typed constant:
const bonusInt int = 5
var c float64 = 2.5 + bonusInt // ERROR: tipe tidak cocok (float64 vs int)
This one fails with a type mismatch (float64 vs int).
Rule of thumb: leave constants untyped unless you actually want to restrict them.
Constant expressions
A constant can be computed from other constants, because they're all known at compile time:
const (
detikPerMenit = 60
detikPerJam = detikPerMenit * 60
detikPerHari = detikPerJam * 24
)
But the result of a function call is not a constant:
const akar2 = math.Sqrt(2) // ERROR: bukan ekspresi konstanta
The compiler rejects it because math.Sqrt(2) isn't a constant expression.
Try it yourself
Run the example in the editor with Run. Then try this:
- change
const bonusXP = 25toconst bonusXP int = 25and see what compile error shows up; - add the line
levelMaksimum = 60insidemainand read the error message.