Go Constants #
When you need a value that should never change throughout the execution of a program, you can use a constant.
Constants are unchangeable and read-only values declared using the const
keyword.
✅ Syntax of Declaring a Constant #
const CONSTNAME type = value
👉 Important: The value of a constant must be assigned when declared.
✅ Example: Declaring a Constant #
package main
import "fmt"
const PI = 3.14
func main() {
fmt.Println(PI) // Output: 3.14
}
✅ Constant Rules #
- Constant names follow the same naming rules as variables.
- By convention, constant names are often written in uppercase letters to easily distinguish them.
- Constants can be declared inside and outside functions.
✅ Types of Constants #
1️⃣ Typed Constants #
Declared with an explicit type.
Example: #
package main
import "fmt"
const A int = 1
func main() {
fmt.Println(A) // Output: 1
}
2️⃣ Untyped Constants #
Declared without specifying a type. The type is inferred from the value.
Example: #
package main
import "fmt"
const A = 1
func main() {
fmt.Println(A) // Output: 1
}
✅ Constants Are Read-Only #
Once declared, a constant’s value cannot be changed.
Example: #
package main
import "fmt"
func main() {
const A = 1
A = 2 // ❌ Error: cannot assign to A
fmt.Println(A)
}
⚠️ Result:
./prog.go:8:7: cannot assign to A
✅ Multiple Constants Declaration #
For better organization, you can declare multiple constants in a block.
Example: #
package main
import "fmt"
const (
A int = 1
B = 3.14
C = "Hi!"
)
func main() {
fmt.Println(A) // Output: 1
fmt.Println(B) // Output: 3.14
fmt.Println(C) // Output: Hi!
}
🚀 Using constants improves your program’s readability and prevents accidental changes to important values.