Go Gopher How to Go

Constants

Constants hold values that do not change. They are great for configuration, sizes, and enumerations. One common use for constants is declaring an API_KEY.

💡 Key Points

  • Constants are declared with const and cannot be changed.
  • Numeric constants are high-precision until given a type.
  • You can use constants in expressions; the compiler folds them.
package main

import "fmt"
import "math"

const s string = "constant"

func main() {

  fmt.Println(s)

  const pi = 3.14
  const n = 500000000
  const d = 3e20 / n
  fmt.Println(math.Sqrt(pi))
  fmt.Println(d)
  fmt.Println(int64(d))
  fmt.Println(math.Sin(n))

}
Output:
constant
1.772004514666935
60000000000
-0.28470407323754404

Constants Reference

ConstantTypeValueDescription
sstring"constant"String constant with explicit type
piuntyped float3.14Mathematical constant for π
nuntyped int500000000Large numeric constant
duntyped float3e20 / nComputed constant expression