HTML tutorial
CSS3 tutorial
Bootstrap tutorial
JavaScript tutorial
JQuery tutorial
AngularJS tutorial
React tutorial
NodeJS tutorial
PHP tutorial
Python tutorial
Python3 tutorial
Django tutorial
Linux tutorial
Docker tutorial
Ruby tutorial
Java tutorial
C tutorial
C ++ tutorial
Perl tutorial
JSP tutorial
Lua tutorial
Scala tutorial
Go tutorial
ASP.NET tutorial
C # tutorial
If a variable should have a fixed value that cannot be changed, you can use the const keyword
If a variable should have a fixed value that cannot be changed, you can use the const
keyword.
The const
keyword declares the variable as "constant", which means
that it is unchangeable and read-only.
const CONSTNAME type = value
Note: The value of a constant must be assigned when you declare it.
Here is an example of declaring a constant in Go:
package main
import ("fmt")
const PI = 3.14
func main() {
fmt.Println(PI)
}
There are two types of constants:
Typed constants are declared with a defined type:
package main
import ("fmt")
const A int = 1
func main() {
fmt.Println(A)
}
Untyped constants are declared without a type:
package main
import ("fmt")
const A = 1
func main() {
fmt.Println(A)
}
Note: In this case, the type of the constant is inferred from the value (means the compiler decides the type of the constant, based on the value).
When a constant is declared, it is not possible to change the value later:
package main
import ("fmt")
func main() {
const A = 1
A = 2
fmt.Println(A)
}
Result:
./prog.go:8:7: cannot assign to A
Multiple constants can be grouped together into a block for readability:
package main
import ("fmt")
const (
A int = 1
B = 3.14
C = "Hi!"
)
func main() {
fmt.Println(A)
fmt.Println(B)
fmt.Println(C)
}