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:

Go

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:

Go




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:

Go


Untyped Constants

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

Example:

Go

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:

Go

Result:

Go




Declaring Multiple Constants

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

Example:

Go

Tutorials dojo strip