Code With Go
  • Code With Go
  • 01. What, Who, Why and Where?
  • 02. Compiled vs Interpreted languages
  • 03. Types of Type!
  • 04. Stack and Heap Memory
  • 05. Garbage Collection
  • 06. About Go
  • 07. Go Playground
  • 08. Hello, World!
  • 09. Installing Go
  • 10. Variables
  • 11. Constants
  • 12. Integers
  • 12. Floats
  • 13. Boolean
  • 14. Strings
  • 15. Complex Numbers
  • 16. If Else
  • 17. Switch
  • 18. For
  • 19. User Defined Types
  • 20. Arrays
  • 21. Slices
  • 22. Structs
  • 23. Maps
  • 24. Functions
  • 25. Defer
  • 26. Pointers
  • 27. Methods
  • Resources
    • Resources - Paid
    • Resources - Free
Powered by GitBook
On this page
  • What are constants?
  • Declaring constants
  • Constant Block
  • IOTA
  • From the Docs
  • Blog Posts

Was this helpful?

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
const pi = 3.14

Constant Block

Similar to variable block, we can also have constant block.

main.go
const (
	pi         = 3.14
	daysInWeek = 7
)

IOTA

iota can be used to create enumerated constants. It is also called as constant generator.

main.go

const (
	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.go

const (
	Monday int = iota + 1
	Tuesday
	Wednesday
	Thursday
	Friday
	Saturday
	Sunday
)

func main() {
	fmt.Println(Monday, Tuesday, Wednesday, Thursday, 
	Friday, Saturday, Sunday)
}
// output : 1 2 3 4 5 6 7

From the Docs

Blog Posts

Previous10. VariablesNext12. Integers

Last updated 5 years ago

Was this helpful?

Effective Go - The Go Programming Language
Constants
Logo
Constants - The Go Programming Language
Logo
Iota · golang/go WikiGitHub
Go by Example: Constants and iota
iota: Elegant Constants in Golang - Blog | SpliceBlog | Splice
Logo
Logo