Go Constants
Go (Golang) – Constants
Constants in Go are fixed values whose value cannot be changed once declared.
They are defined using the const keyword.
1️⃣ Declaring Constants
Single Constant
❌ Not allowed:
2️⃣ Typed vs Untyped Constants
Untyped Constant
✔ Flexible
✔ Can be used as int, float, etc.
Typed Constant
✔ Strict type
3️⃣ Multiple Constants Declaration
Same Type
Using const Block (Recommended)
4️⃣ Constant Expressions
Constants can be computed at compile time.
5️⃣ iota – Special Constant Generator
iota is used to create incrementing constants automatically.
Example 1: Simple Counter
Example 2: Custom Start
6️⃣ iota with Skipped Values
7️⃣ iota with Bitwise Flags (Common Use)
8️⃣ Where Constants Can Be Used
✔ Global scope
✔ Local scope
✔ In expressions
✔ As enum-like values
❌ Cannot be declared using :=
9️⃣ Constants vs Variables
| Feature | Constant | Variable |
|---|---|---|
| Keyword | const |
var |
| Value Change | ❌ No | ✅ Yes |
| Runtime Assignment | ❌ No | ✅ Yes |
:= allowed |
❌ No | ✅ Yes |
10️⃣ Best Practices
✔ Use constants for fixed values
✔ Use iota for enums
✔ Prefer const over var where possible
✔ Group related constants together
Summary
-
Constants are immutable
-
Evaluated at compile time
-
iotasimplifies enum creation -
Improves safety and readability
