11. Constants
Can not change me

What are constants?

A const declaration defines named values that look syntactically like variables but whose value is constant.Instead of the var keyword, we use the const keyword.A value must be assigned while declaring constants.Constants only exists during compile time!

Declaring constants

Constants are declared using const keyword.
main.go
1
const pi = 3.14
Copied!

Constant Block

Similar to variable block, we can also have constant block.
main.go
1
const (
2
pi = 3.14
3
daysInWeek = 7
4
)
Copied!

IOTA

iota can be used to create enumerated constants. It is also called as constant generator.
main.go
1
const (
2
Sunday int = iota
3
)
4
5
func main() {
6
fmt.Println(Sunday)
7
}
Copied!
Benefits of using iota is that it will increment itself for next const declaration in same const block.
main.go
1
const (
2
Monday int = iota + 1
3
Tuesday
4
Wednesday
5
Thursday
6
Friday
7
Saturday
8
Sunday
9
)
10
11
func main() {
12
fmt.Println(Monday, Tuesday, Wednesday, Thursday,
13
Friday, Saturday, Sunday)
14
}
15
// output : 1 2 3 4 5 6 7
Copied!

From the Docs

Effective Go - The Go Programming Language
Constants

Blog Posts

Constants - go.dev
Iota · golang/go Wiki
GitHub
Go by Example: Constants and iota
iota: Elegant Constants in Golang - Blog | Splice
Blog | Splice
Last modified 2yr ago