Go course

Constants and FormattingConstant Blocks and Untyped Constants

Go

Display

Theme

Constants and Formatting · Code example

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 = 25 to const bonusXP int = 25 and see what compile error shows up;
  • add the line levelMaksimum = 60 inside main and read the error message.
main.go
package main

import "fmt"

const (
	namaGame      = "Petualangan Nusantara"
	levelMaksimum = 50
	nyawaAwal     = 3
)

const (
	detikPerMenit = 60
	detikPerJam   = detikPerMenit * 60
	detikPerHari  = detikPerJam * 24
)

// Konstanta tanpa tipe: bisa dipakai sebagai int maupun float64.
const bonusXP = 25

func main() {
	var xpPemain int = 120 + bonusXP
	var pengali float64 = 1.5 * bonusXP

	fmt.Println("Game:", namaGame)
	fmt.Println("Level maksimum:", levelMaksimum, "| Nyawa awal:", nyawaAwal)
	fmt.Println("XP pemain:", xpPemain)
	fmt.Println("XP bonus event:", pengali)
	fmt.Println("Satu hari =", detikPerHari, "detik")
}

Output

Go runtime not loaded yet

Press Run to see what the program prints.

Ctrl/Cmd + Enter: Run · Ctrl/Cmd + S: tidy the code (gofmt)