Grokking Go
Vote

0% completed

​

Constants in Go

What is a Constant?

Syntax

Example: Declaring Constants

Constants vs. Variables

Declaring Multiple Constants

Example: Declaring Multiple Constants

Special Constants: iota

Example: Using "iota"

Limitations of Constants

Constants in Go are used to store fixed values that do not change throughout the execution of a program. Unlike variables, once a constant is assigned a value, it cannot be modified.

In this lesson, we will learn about declaring constants, their syntax, types, and key differences from variables.

What is a Constant?

A constant is a named value that remains unchanged during program execution. Constants are useful when you need fixed values like mathematical constants (PI), configuration settings, or predefined messages.

Syntax

const constantName dataType = value
  • const → Keyword to declare a constant.
Image

Example: Declaring Constants

Go
Go

. . . .
  • PI is a float64 constant with a fixed value of 3.14159.
  • greeting is declared without specifying a type, and Go infers it as a string.
  • The values remain unchanged throughout the program.

Constants vs. Variables

FeatureConstants (const)Variables (var)
Value ModificationCannot be changed after assignmentCan be modified anytime
Memory UsageMore efficient, computed at compile-timeStored in memory at runtime
Type InferenceAllowedAllowed
UsageUsed for fixed valuesUsed for dynamic values

Declaring Multiple Constants

Multiple constants can be declared inside a const block for better organization.

const ( constant1 dataType = value1 constant2 dataType = value2 constant3 = value3 )

Example: Declaring Multiple Constants

Go
Go

. . . .
  • Multiple constants are declared inside a const block, making the code cleaner and more readable.
  • PI, LANGUAGE, and YEAR hold fixed values that cannot be changed.

Special Constants: iota

Go provides a special constant called iota, which is used to create sequential values automatically.

Example: Using "iota"

Go
Go

. . . .
  • iota starts at 0 and increments by 1 for each constant in the same block.
  • A = 0, B = 1, and C = 2 are automatically assigned.

Limitations of Constants

  • Cannot use := for constants (short declaration is only for variables).
  • Cannot be assigned values at runtime (e.g., user input or function return values).
  • Cannot modify their value after declaration.

In the next lesson, we will explore Variable Naming Rules in Go, which covers best practices and restrictions for naming variables effectively.

Reading Progress

0%


Vote for new content

On This Page

What is a Constant?

Syntax

Example: Declaring Constants

Constants vs. Variables

Declaring Multiple Constants

Example: Declaring Multiple Constants

Special Constants: iota

Example: Using "iota"

Limitations of Constants