Constants are used to represent fixed values; their values cannot be changed at a later stage in the program. Any attempt to change the value of a constant will cause a runtime panic.
To declare a constant and give it a name, the const
keyword is used.
const myValue = "Hello World"
const country, code = "Pakistan", 92
Constants cannot be declared using the
:=
syntax.
The following code shows how to declare constant values in our code:
package mainimport "fmt"const Pi = 3.14func main() {const name = "John"fmt.Println("Hello", name)fmt.Println("Value of Pi is", Pi)const myval = truefmt.Println("Variable myval contains:", myval)}
In Golang, constants are typed when you explicitly specify the type in the declaration:
const my_typed_const int = 20
With typed constants, all the flexibility that comes with untyped constants (like assigning them to any variable of compatible type or mixing them in mathematical operations) is lost.
In Golang, all constants are untyped unless they are explicitly given a type at declaration.
const my_untyped_const = 20
Untyped constants allow for flexibility. They can be assigned to any variable of compatible type or mixed into mathematical operations.
Free Resources