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!
Constants are declared using const
keyword.
main.goconst pi = 3.14
Similar to variable block, we can also have constant block.
main.goconst (pi = 3.14daysInWeek = 7)
iota
can be used to create enumerated constants. It is also called as constant generator.
main.goconst (Sunday int = iota)func main() {fmt.Println(Sunday)}
Benefits of using iota is that it will increment itself for next const declaration in same const block.
main.goconst (Monday int = iota + 1TuesdayWednesdayThursdayFridaySaturdaySunday)func main() {fmt.Println(Monday, Tuesday, Wednesday, Thursday,Friday, Saturday, Sunday)}// output : 1 2 3 4 5 6 7