Constants

This lesson explains how to declare const type variables.

We'll cover the following

Declaration

Constants are declared like variables, but with the const keyword.

Constants can only be a character, string, boolean, or numeric values and cannot be declared using the := syntax. An untyped constant takes the type needed by its context.

Press + to interact
const Pi = 3.14
const (
StatusOK = 200
StatusCreated = 201
StatusAccepted = 202
StatusNonAuthoritativeInfo = 203
StatusNoContent = 204
StatusResetContent = 205
StatusPartialContent = 206
)

Let’s take a look at an example below demonstrating this concept.

Example

Press + to interact
package main
import "fmt"
const (
Pi = 3.14
Truth = false
Big = 1 << 62
Small = Big >> 61
)
func main() {
const Greeting = "ハローワールド" //declaring a constant
fmt.Println(Greeting)
fmt.Println(Pi)
fmt.Println(Truth)
fmt.Println(Big)
}

Note: The left-shift operator (<<) shifts its first operand left by the number of bits specified by its second operand. The type of the second operand must be an int or a type that has a predefined implicit numeric conversion to int. The right-shift operator (>>) shifts its first operand right by the number of bits specified by its second operand.

Now that you know how to declare constants from the above examples. Let’s move on and read about printing constants/variables.