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.
const Pi = 3.14const (StatusOK = 200StatusCreated = 201StatusAccepted = 202StatusNonAuthoritativeInfo = 203StatusNoContent = 204StatusResetContent = 205StatusPartialContent = 206)
Let’s take a look at an example below demonstrating this concept.
Example
package mainimport "fmt"const (Pi = 3.14Truth = falseBig = 1 << 62Small = Big >> 61)func main() {const Greeting = "ハローワールド" //declaring a constantfmt.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 anint
or a type that has a predefined implicit numeric conversion toint
. 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.