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

const PI = 3.14
const appName string = "GoApp"

❌ Not allowed:

PI = 3.1415 // error: cannot assign to PI

2️⃣ Typed vs Untyped Constants

Untyped Constant

const x = 10

✔ Flexible
✔ Can be used as int, float, etc.

Typed Constant

const y int = 10

✔ Strict type


3️⃣ Multiple Constants Declaration

Same Type

const a, b, c int = 1, 2, 3

Using const Block (Recommended)

const (
host = "localhost"
port = 8080
debug = true
)

4️⃣ Constant Expressions

Constants can be computed at compile time.

const area = PI * 10 * 10

5️⃣ iota – Special Constant Generator

iota is used to create incrementing constants automatically.

Example 1: Simple Counter

const (
A = iota // 0
B // 1
C // 2
)

Example 2: Custom Start

const (
Sun = iota + 1 // 1
Mon // 2
Tue // 3
)

6️⃣ iota with Skipped Values

const (
_ = iota
Read // 1
Write // 2
Exec // 3
)

7️⃣ iota with Bitwise Flags (Common Use)

const (
Read = 1 << iota // 1
Write // 2
Exec // 4
)

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

  • iota simplifies enum creation

  • Improves safety and readability

You may also like...