ELEVATE YOUR BUSINESS WITH

Limitless customization options & Elementor compatibility let anyone create a beautiful website with Valiance.

Constants in GoLang

SELECT * FROM `itio_tutorial_master` WHERE `tutorial_menu`='1' AND `tutorial_submenu`='10' AND `tutorial_status`=1 LIMIT 1

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

  1. Constants must be initialized with a compile-time constant.
  2. Constants cannot be the result of runtime computation.
  3. 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.

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql
postgresql
mariaDB
sql