Go Constants
Links:
- 103 Golang Index
- Go - Basics
Constants¶
- A constant belongs to the compile time and it's created at compile time. It's value can not be changed while the program is running.
- Example:
x,y := 6,0; fmt.Printf(x/y)
- This will throw run compile time error.
- Example:
- Another advantage of using constants is that Go can not detect runtime errors at compile-time but constants belong to compile time so errors can be detected earlier
- Constants can be unused unlike variables and compiler won't give any error.
-
Multiple declarations
const n1, m1 int = 5,6
const n1, m1 = 5,6
- Grouped constant
-
In a grouped constant a constant repeats the previous one
Rules for constants¶
- Variables can be left uninitialised after declaring but constants must be initialised after declaring them.
You cannot initialise the constants at runtime
const a int = Math.pow(3,4)
- This is incorrect since function calls belong to runtime
- You cannot use variables to initialise constants. Eg:
t := 6; const tc = t
- Incorrect. This is because variables belong to runtime. - We can use built in functions like
len
.const a = len("hello")
- You can use expressions if they are constant expressions since it can be evaluated at compile time.
You cannot declare constants of type array
There are ONLY boolean constants, rune constants, integer constants, floating-point constants, complex constants, and string constants.
Typed and Untyped Constants¶
const a int = 65
- Typed constantconst a = 56
- Untyped constant
Untyped constants give us greater flexibility
Iota¶
- It is number generator for constants
iota
keyword represents successive keyword integers.- By default iota starts with 0.
_
can be used to skip values
Last updated: 2022-05-21