Constants

const block

The const keyword declares values that never change, and a const block groups related values in one place.

The detailed guide lives in the article about constants, while the pattern below covers everyday use.

package main import "fmt" const ( appName = "course" maxRetries = 3 pi = 3.14159 ) func main() { fmt.Println(appName, maxRetries, pi) }

go run .

course 3 3.14159

iota enumerations

The iota identifier counts lines inside a const block starting from zero, which is ideal for enumerations such as days or statuses.

Repeated lines inherit the expression above, so only the first line needs the explicit iota.

package main import "fmt" const ( sun = iota mon tue ) func main() { fmt.Println(sun, mon, tue) }

go run .

0 1 2

Typed vs untyped

A constant with an explicit type works only with that type, while an untyped constant adapts to int or float64 or string as the context requires.

Prefer untyped constants for math and configuration defaults, and add a type when the value must stay fixed to one representation.

package main import "fmt" const ratio = 0.5 const limit int = 10 func main() { fmt.Println(ratio + 1) fmt.Println(ratio + 0.25) fmt.Println(limit + 5) }

go run .

1.5
0.75
15

When constants win

Choose constants for values that are known before compilation and must never change during the run: mathematical factors, limits, status codes, and configuration defaults.

Constants document intent, let the compiler check misuse early, and remove a whole class of accidental reassignment bugs.

Next: Types

Article author: Arthur Isaev