Deep Drive On Constants

Part of Golang Mastery course

~15 min read
Interactive
Hands-on
Beginner-friendly

If you wanted to find out whether const was a keyword, how would you do so?

example.go
package main
 
import (
string">"fmt"
)
 
const
 
func main() {
fmt.Println(string">"Hello, playground")
}
 
 

The Go Programming Language Specification is a great place to start. The Keywords section holds the answer.

break default func interface select case defer go map struct chan else goto package switch const fallthrough if range type continue for import return var

Make a few constants using the Go playground. The Go compiler will figure out what type they are for you.

example.go
package main
 
import (
string">"fmt"
)
 
const a = 42
const b = 42.78
const c = string">"James Bond"
 
func main() {
fmt.Println(a)
fmt.Println(b)
fmt.Println(c)
fmt.Printf(string">"%T\n", a)
fmt.Printf(string">"%T\n", b)
fmt.Printf(string">"%T\n", c)
}
 
 

An alternative way to declare several constants and assign values is using similar syntax to our import statement.

example.go
package main
 
import (
string">"fmt"
)
 
const (
a = 42
b = 42.78
c = string">"James Bond"
)
 
func main() {
fmt.Println(a)
fmt.Println(b)
fmt.Println(c)
fmt.Printf(string">"%T\n", a)
fmt.Printf(string">"%T\n", b)
fmt.Printf(string">"%T\n", c)
}
 
 

playground

If we want to specify the type of our constants, we can. Currently, they are untyped and are known as constants of a kind. That gives the compiler a bit of flexibility, because with constants of a kind, or constants which are untyped, the compiler decides which types to assign which values to. When it is typed, it doesn't have that flexibility.

example.go
package main
 
import (
string">"fmt"
)
 
const (
a int = 42
b float32 = 42.78
c string = string">"James Bond"
)
 
func main() {
fmt.Println(a)
fmt.Println(b)
fmt.Println(c)
fmt.Printf(string">"%T\n", a)
fmt.Printf(string">"%T\n", b)
fmt.Printf(string">"%T\n", c)
}
 
 

playground

Your Progress

12 of 103 modules
12%
Started12% Complete
Previous
SpaceComplete
Next