Tuesday, December 1, 2020

Constants in Go

Want to know more about constants in Go? Read to understand

On a previous post we discussed variables in Go. We also learned what zero values are. Today we will focus on understanding what are constants in Go and how to use them.

What is a constant?

Almost every programming language has the concept of constants. Constants are variables that hold immutable values, values that you can't change when your program is running. In Go, they're declared by using the const keyword and can only hold values that the compiler knows at compile time.

Let's see some examples:

// declare one const named maxAge of type int
const maxAge int = 100

// declare bool const
const active = false

// declare multiple consts at the same time
const (
      siteName   = "Golang4us"
      email = "mail@mail.com"
)

// declare a const maxRecords assigning a value to it
const maxRecords = 200 * 10

What cannot be a constant

Knowing what can be a constant is only part of the equation. The other part is knowing what cannot. Since in order to be a constant, the compiler has to know its value at compile time, anything calculated or available at runtime cannot be. And that applies to common types like arrays, slices, maps or structs.

Typed and Untyped Constants

There are two ways to declare constants in Go:

  1. typed: defines the type and can only be assigned to a variable of the same type
  2. untyped: works as a literal. Has no type but can have its type inferred by the compiler
You can see how they work in the examples below:
// a typed constant
const a name = "Adam"

// an untyped constant
const age = 42

As you may expect, although no type was specified for the variable age, the compiler will infer via its assigned value (42) that its type is int.

Checking a constant's type

In case you want, you can verify the types of your constants by using the %T formatter. For example, the program below would print: Age 42 is of type int
package main

import (
"fmt"
)

func main() {
const age = 42
fmt.Printf("Age %v is of type %T", age, age)
}

When to use constants?

But when and why use constants? The rule of thumb is to use them whenever you need to reference a value that doesn't change. You could definitely hardcode constants in your code but setting them in constants in your code keeps the code DRY, making it more readable, refactorable and maintainable.

Reference

See Also

Any comment about this page? Please contact us on Twitter

Featured Article

Pointers in Go

Understand all about declaring and using pointers in Go If you're coming from Python, Java, JavaScript, C# and others, tal...

Popular Posts