bugl
bugl
HomeLearnPatternsPathsSearchPremium
HomeLearnPatternsPaths
Learn/Go/Go Tutorial
Go•Go Tutorial

Go Constants

If a variable should have a fixed value that cannot be changed, you can use the const keyword.

The const keyword declares the variable as "constant", which means that it is unchangeable and read-only .

Syntax

const
CONSTNAME type = value

Note

The value of a constant must be assigned when you declare it.

Declaring a Constant

Here is an example of declaring a constant in Go:

Example

package main
import ("fmt")
const PI = 3.14
func main() {
  fmt.Println(PI)
}

Constant Rules

  • Constant names follow the same naming rules as variables
  • Constant names are usually written in uppercase letters (for easy identification and differentiation from variables)
  • Constants can be declared both inside and outside of a function

Constant Types

There are two types of constants

  • Typed constants
  • Untyped constants

Typed Constants

Typed constants are declared with a defined type:

Example

package main
import ("fmt")
const A int = 1
func main() {
  fmt.Println(A)
}

Untyped Constants

Untyped constants are declared without a type:

Example

package main
import ("fmt")
const A = 1
func main() {
  fmt.Println(A)
}

Note

In this case, the type of the constant is inferred from the value (means the compiler decides the type of the constant, based on the value).

Constants: Unchangeable and Read-only

When a constant is declared, it is not possible to change the value later:

Example

package main
import ("fmt")
func main() {
  const A = 1
  A = 2
  fmt.Println(A)
}

Multiple Constants Declaration

Multiple constants can be grouped together into a block for readability:

Example

package main
import ("fmt")
const ( A int = 1
B = 3.14
C = "Hi!" )
func main() {
  fmt.Println(A)
  fmt.Println(B)
  fmt.Println(C)
}

Previous

Go Variable Naming Rules

Next

Go Output Functions

This chapter

Overview
39

Lessons

95m

Read time

1. Go Tutorial2. Go Introduction3. Go Getting Started4. Go Syntax5. Go Comments6. Go Variables7. Go Multiple Variable Declaration8. Go Variable Naming Rules9. Go Constants10. Go Output Functions11. Go Formatting Verbs12. Go Data Types13. Go Boolean Data Type14. Go Integer Data Types15. Go Float Data Types16. Go String Data Type17. Go Arrays18. Go Slices19. Go Access, Change, Append and Copy Slices20. Go Operators21. Go Arithmetic Operators22. Go Assignment Operators23. Go Comparison Operators24. Go Logical Operators25. Go Bitwise Operators26. Go Conditions27. Go if statement28. Go if else Statement29. Go else if Statement30. Go Nested if Statement31. Go switch Statement32. Go Multi-case switch Statement33. Go For Loops34. Go Functions35. Go Function Parameters and Arguments36. Go Function Returns37. Go Recursion Functions38. Go Struct39. Go Maps

On this page

Declaring a ConstantConstant RulesConstant TypesTyped ConstantsUntyped ConstantsConstants: Unchangeable and Read-onlyMultiple Constants Declaration