Summary: in this tutorial, you will learn how to use Go constants to represent values that cannot be changed throughout the program.
Constants are identifiers whose values cannot be changed during the execution of the program. Constants can be useful for values that are known at compile time and should remain unchanged.
In Go, you can define constants for numbers, strings, and booleans. Constant values can be literals or compile-time functions of other constants.
Declaring constants
To declare constants in Go, you use the const
keyword. Unlike a variable, you need to declare and assign a value to a constant immediately:
const constantName type = value
Code language: Go (go)
The type
can be of numeric types, strings, and booleans. For example:
const salesTax float64 = 0.08
Code language: Go (go)
Since Go can infer the type of the salesTax
using the initial value, you can make the code more concise as follows:
const salesTax = 0.08
Code language: Go (go)
As mentioned earlier, you cannot change the value of a constant. The following will result in a compile error:
const salesTax = 0.08
salesTax = 0.09 // error
Code language: Go (go)
To declare multiple constants at the same time, you can use the const
block:
const (
salesTax = 0.08
discount = 0.05
greeting = "Hi, there"
)
Code language: Go (go)
The following example shows how to declare a constant based on the value of another constant:
package main
import "fmt"
func main() {
const (
message = "Hi"
size = len(message) // 2
)
fmt.Println(message, size)
}
Code language: JavaScript (javascript)
Output:
Hi 2
Summary
- Use Go constants to represent values that do not change throughout the program.