What is const in Go: Explanation and Usage
const in Go defines a constant value that cannot change during program execution. Constants are fixed values like numbers or strings, set at compile time and used to make code clearer and safer.How It Works
Think of const in Go as a label you stick on a value that never changes, like a permanent price tag on a product. Once you set a constant, you cannot change it later in your program. This helps avoid mistakes where a value might accidentally get changed.
Constants in Go are determined when you write your code, not while the program runs. This means the computer knows these values ahead of time, which can make your program faster and more reliable. You can use constants for things like fixed numbers, names, or settings that should stay the same.
Example
This example shows how to declare and use a constant in Go. The constant Pi is set to 3.14 and used to calculate the area of a circle.
package main import "fmt" func main() { const Pi = 3.14 radius := 5.0 area := Pi * radius * radius fmt.Println("Area of circle:", area) }
When to Use
Use const when you have values that should never change, like mathematical constants (e.g., Pi), configuration values, or fixed strings (e.g., app version). This makes your code easier to read and prevents accidental changes that could cause bugs.
For example, if you have a tax rate or a maximum number of users allowed, defining these as constants helps keep your program safe and clear.
Key Points
- Constants hold fixed values that cannot change.
- They are set at compile time, not at runtime.
- Use them for values like numbers, strings, or booleans that stay the same.
- Constants improve code safety and readability.
Key Takeaways
const defines fixed values that never change during program execution.