In the previous tutorial, we saw how to define variables in Google Go. In today’s tutorial, we check out how we can declare constants and enumerated constants in Google Go.
Constants
The types of constants available in Go programming are boolean constants, integer constants, floating-point constants, complex constants, and string constants. Constants in Go are created at compile time, even when defined as locals in functions.
Constants are declared similar to variables except that the const keyword is used. Also we cannot use the idiom (using :=) as done for variable declaration.
Below are examples of declaring different types of constants in Go programming.
const Pi float64 = 3.14159265358979323846 //typed floating-point constant
const zero = 0.0 // untyped floating-point constant
const (
size int64 = 1024 //typed integer constant
eof = -1 // untyped integer constant
)
const a, b, c = 3, 4, "foo" // a = 3, b = 4, c = "foo", untyped integer and string constants
const u, v float = 0, 3 // u = 0.0, v = 3.0
const sum = 1 – 0.707i ///complex constant
const flag bool = true
Enumerated Constants
In Go, enumerated constants are created using the iota enumerator. This can be considered similar to enumeration in C. It is reset to 0 whenever the reserved word const appears in the source and increments after each use of iota as shown below.
const ( // iota is reset to 0
c0 = iota // c0 == 0
c1 = iota // c1 == 1
c2 = iota // c2 == 2
)
const (
a = 1 << iota // a == 1 (iota has been reset)
b = 1 << iota // b == 2
c = 1 << iota // c == 4
)
const (
u = iota * 42 // u == 0 (untyped integer constant)
v float = iota * 42 // v == 42.0 (float constant)
w = iota * 42 // w == 84 (untyped integer constant)
)
const x = iota // x == 0 (iota has been reset)
const y = iota // y == 0 (iota has been reset)
Related Posts:
Tags: google go

