
Constants in GoLang
Constants in Go are immutable values that are known at compile time and remain unchanged during the program's execution. They are declared using the const
keyword.
1. Basic Declaration
Constants can be of simple data types like int
, float
, string
, or boolean
.
func main() { package mainimport "fmt"func main() { package mainimport "fmt"func main() { const TypedInt int = 42 // Typed constant const UntypedFloat = 3.14 // Untyped constant var x float64 = UntypedFloat // Allowed: Untyped constants are flexible fmt.Println("TypedInt:", TypedInt) fmt.Println("UntypedFloat as float64:", x)}
4. Constant Expressions
Constants can be used in expressions if all operands are constants. The result is also a constant.
func main() { package mainimport "fmt"func main() { package mainimport "fmt"func main() { package mainimport "fmt"func main() { const ConstantValue = 100 var VariableValue = 100 fmt.Println("Before update, VariableValue:", VariableValue) // VariableValue can be updated VariableValue = 200 fmt.Println("After update, VariableValue:", VariableValue) // Uncommenting below will cause an error // ConstantValue = 200}
7. Limitations
- Constants must be initialized with a compile-time constant.
- Constants cannot be the result of runtime computation.
- Arrays, slices, and maps cannot be constant.
Example: Practical Usage of Constants
const ( BasePrice = 100.0 TaxRate = 0.05 Discount = 0.10)func main() { priceAfterTax := BasePrice + (BasePrice * TaxRate) finalPrice := priceAfterTax - (priceAfterTax * Discount) fmt.Printf("Final Price after tax and discount: %.2f\n", finalPrice)}
Output
Final Price after tax and discount: 94.50
Constants in Go are essential for creating fixed values that improve code readability, maintainability, and performance.