Constants in Go

Introduction

Constant values must be defined before compilation.
br> You cannot assign a constant a value returned by a function, since it is not yet known at compile time.

A constant must be assigned a value right at the time of declaration. (Similar to 2)

Before reading this article it is advisable to read:

Declaring a constant

Example

package main import ( "fmt" ) func main() { const pi = 3.1415 fmt.Println(pi) }

go run main.go

3.1415

Automatic type assignment

If you do not specify a type at declaration, you can use one constant with different types.

package main import ( "fmt" ) func main() { const c = 5 fmt.Println(c) fmt.Println(c + 4) fmt.Println(c + 0.5) }

go run main.go

5 9 5.5

First Go determined the constant c as int, then as float

If you explicitly set the type of the constant as int there will be an error

const c int = 5

./main.go:14:19: 0.5 (untyped float constant) truncated to int

You can get rid of the error by converting the constant in advance

fmt.Println(float32(c) + 0.5)

iota

You can assign consecutive integer values to constants using iota

package main import ( "fmt" ) const ( a = iota // 0 b = iota // 0 + 1 = 1 c = iota // 1 + 1 = 2 six = iota + 3 // 2 + 1 + 3 = 6 // Bitwise shift sixteen = 1 << iota // 1 * 2 * 2 * 2 * 2 // Automatic value assignment x = iota + 20 // 4 + 1 + 20 = 25 y // 25 + 1 = 26 z // 26 + 1 = 27 ) // In a new const block iota resets to zero const ( zero = iota one two ) func main() { fmt.Println(a, b, c, six, sixteen, x, y, z, zero, one, two) }

go run main.go

0 1 2 6 16 25 26 27 0 1 2

Article author: Andrei Olegovich