9.deep drive on Constants - programming in go

Posted on Mar 04, 2019   ∣  2 min read  ∣  GO

9. deep drive on Constants - programming in go

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

package main

import (
	"fmt"
)

const

func main() {
	fmt.Println("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.

package main

import (
	"fmt"
)

const a = 42
const b = 42.78
const c = "James Bond"

func main() {
	fmt.Println(a)
	fmt.Println(b)
	fmt.Println(c)
	fmt.Printf("%T\n", a)
	fmt.Printf("%T\n", b)
	fmt.Printf("%T\n", c)
}

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

package main

import (
	"fmt"
)

const (
	a = 42
	b = 42.78
	c = "James Bond"
)

func main() {
	fmt.Println(a)
	fmt.Println(b)
	fmt.Println(c)
	fmt.Printf("%T\n", a)
	fmt.Printf("%T\n", b)
	fmt.Printf("%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.

package main

import (
	"fmt"
)

const (
	a int     = 42
	b float32 = 42.78
	c string  = "James Bond"
)

func main() {
	fmt.Println(a)
	fmt.Println(b)
	fmt.Println(c)
	fmt.Printf("%T\n", a)
	fmt.Printf("%T\n", b)
	fmt.Printf("%T\n", c)
}

playground