Go Constants

In Go, constants are used for values that should remain unchanged throughout the program. These are declared using the const keyword, which ensures the value remains constant and read-only.

Tutorials dojo strip



Syntax for Declaring Constants

The general syntax for defining a constant is:

const CONSTANT_NAME type = value

Note: A constant must always be assigned a value at the time of declaration.




Declaring a Constant

The following example demonstrates how to declare and use a constant in Go:

package main

import ("fmt")

const YAMAHA_PI = 3.14

func main() {
  fmt.Println(YAMAHA_PI)
}




Rules for Constants

  • Constants follow the same naming rules as variables.
  • By convention, constant names are written in uppercase letters for better distinction from variables.
  • Constants can be declared either inside or outside a function.




Types of Constants

Constants in Go can be categorized into two types: Typed Constants and Untyped Constants.

Typed Constants

Typed constants are defined with an explicit type.

Example:

package main

import ("fmt")

const HONDA_SPEED int = 120

func main() {
  fmt.Println(HONDA_SPEED)
}


Untyped Constants

Untyped constants are declared without specifying a type. The compiler determines the type based on the assigned value.

Example:

package main

import ("fmt")

const SUZUKI_CC = 150

func main() {
  fmt.Println(SUZUKI_CC)
}

Note: In this case, the type of the constant is inferred automatically by the compiler.




Constants: Unchangeable and Read-only

Once a constant is defined, its value cannot be altered. Attempting to do so will result in an error.

Example:

package main

import ("fmt")

func main() {
  const MAX_RIDERS = 2
  MAX_RIDERS = 3
  fmt.Println(MAX_RIDERS)
}

Result:

./prog.go:8:7: cannot assign to MAX_RIDERS




Declaring Multiple Constants

To improve readability, multiple constants can be grouped into a block.

Example:

package main

import ("fmt")

const (
  YAMAHA_PRICE int = 150000
  HONDA_PRICE = 120000
  SUZUKI_PRICE = "Affordable"
)

func main() {
  fmt.Println(YAMAHA_PRICE)
  fmt.Println(HONDA_PRICE)
  fmt.Println(SUZUKI_PRICE)
}

Tutorials dojo strip
Scroll to Top