- 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.
x,y := 6,0; fmt.Printf(x/y)- This will throw run compile time error.
- 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.
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
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 constant
const a = 56- Untyped constant
Untyped constants give us greater flexibility
- It is number generator for constants
iotakeyword represents successive keyword integers.
- By default iota starts with 0.
_can be used to skip values
Last updated: 2022-05-21