Constants syntax

I always have a hard time remembering the syntax of declaring constants in Go. So here’s some reminders to myself.

It is possible to declare constants one per line like you’d expect. Note that the there are typed and untyped constants as shown here below.

package main

import "fmt"

const vermKnid string = "scram"
const fox = "foxes likes loxes"

func main() {
	fmt.Println(vermKnid)
	fmt.Println(fox)
}

But you can also use a constant declaration group, which does the same thing but is easier to read if you’re declaring a bunch of constants.

package main

import "fmt"

const (
	vermKnid string = "scram"
	fox             = "foxes likes loxes"
)

func main() {
	fmt.Println(vermKnid)
	fmt.Println(fox)
}

Global vs local constants

It is possible to declare constants both globally and locally (within a function). This is not unexpected because the same is possible with variables.

package main

import "fmt"

const vermKnid string = "scram"

func main() {
	const fox = "foxes likes loxes"

	fmt.Println(vermKnid)
	fmt.Println(fox)
}

What types can be constants?

Only some types can be declared as constants. These are:

  • boolean
  • numerics
  • strings

Typed vs untyped constants

You don’t have to declare a type when declaring a constant. These are called “untyped constants”. The default type of an untyped constant is the same as the thing being bound to it.

Per this article, the default types are:

  • The default type of a string literal is string.
  • The default type of a boolean literal is bool.
  • The default type of an integer literal is int.
  • The default type of a rune literal is rune (a.k.a., int32).
  • The default type of a floating-point literal is float64.
  • If a literal contains an imaginary part, then its default type is complex128.

I’ve shown examples of both typed and untyped constants above.