0% completed
Constants in Go
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
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.
Example: Declaring Constants
PIis afloat64constant with a fixed value of3.14159.greetingis declared without specifying a type, and Go infers it as astring.- The values remain unchanged throughout the program.
Constants vs. Variables
| Feature | Constants (const) | Variables (var) |
|---|---|---|
| Value Modification | Cannot be changed after assignment | Can be modified anytime |
| Memory Usage | More efficient, computed at compile-time | Stored in memory at runtime |
| Type Inference | Allowed | Allowed |
| Usage | Used for fixed values | Used 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
- Multiple constants are declared inside a
constblock, making the code cleaner and more readable. PI,LANGUAGE, andYEARhold 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"
iotastarts at 0 and increments by 1 for each constant in the same block.A = 0,B = 1, andC = 2are 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%
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