Constants hold values that do not change while the program runs. They help keep important values safe and easy to use.
When you have a value like Pi that never changes.
To name fixed settings like maximum number of users.
To avoid repeating the same number or text in many places.
When you want to make your code easier to read with meaningful names.
Syntax
Go
const name type = value
You can omit the type if Go can guess it from the value.
Constants must be assigned a value when declared and cannot change later.
Examples
Defines a constant named Pi with type float64 and value 3.14.
Go
const Pi float64 = 3.14
Defines a string constant Greeting without specifying type explicitly.
Go
const Greeting = "Hello"
Defines multiple constants together using parentheses.
Go
const (
MaxUsers = 100
Version = 1.0
)
Sample Program
This program uses constants Pi and Greeting to print fixed messages. The values do not change anywhere in the program.
Go
package main
import"fmt"
const Pi = 3.14159
const Greeting = "Welcome to Go!"
func main() {
fmt.Println(Greeting)
fmt.Println("Pi is approximately", Pi)
}
OutputSuccess
Important Notes
Constants can be numbers, strings, or booleans.
You cannot use variables to set constant values.
Constants help prevent accidental changes to important values.
Summary
Constants store fixed values that do not change.
They make code safer and easier to understand.
Use const keyword to declare constants in Go.
Practice
(1/5)
1. What is the purpose of using const in Go programming?
easy
A. To declare a value that cannot be changed
B. To declare a variable that can change
C. To create a function
D. To start a loop
Solution
Step 1: Understand the role of const
The const keyword is used to declare constants, which are fixed values that cannot be changed after being set.
Step 2: Compare options with the definition
To declare a value that cannot be changed correctly states that const declares a value that cannot be changed, while other options describe unrelated concepts.
Final Answer:
To declare a value that cannot be changed -> Option A
Quick Check:
Constants = fixed values [OK]
Hint: Constants hold fixed values, variables do not change [OK]
Common Mistakes:
Confusing constants with variables
Thinking const declares functions
Assuming const starts loops
2. Which of the following is the correct way to declare a constant named Pi with value 3.14 in Go?
easy
A. const Pi = 3.14
B. let Pi = 3.14
C. Pi := 3.14
D. var Pi = 3.14
Solution
Step 1: Recall Go syntax for constants
In Go, constants are declared using the const keyword followed by the name and value.
Step 2: Identify the correct syntax
const Pi = 3.14 uses const Pi = 3.14, which is the correct syntax. Options A and C declare variables, and B uses invalid Go syntax.
Final Answer:
const Pi = 3.14 -> Option A
Quick Check:
const keyword = correct declaration [OK]
Hint: Use const keyword for fixed values, not var or := [OK]