Working with Constants in Go

10.25.2021

Intro

Constants are variables that have a fixed value and cannot be changed. They are often use to keep static values that you don't want changed later on. For example, you may have a size for a cache limit that should be changed during the run time of your program. In this article, we will learn how to use constants in Go.

Setting Up

Let's start be creating a new file

touch main.go

We can then add the following code.

package main

import "fmt"

func main() {
   fmt.Println("Hello!")
}

We can run the code using the following.

go run main.go

Declaring Constants

We can declare constants similar to how we declare normal variables. The difference is that we use the const keyword. Here is an example.

package main

import "fmt"

func main() {
   const SIZE int = 10
   fmt.Printf(SIZE)   
}

Run this program with the following:

go run main.go

They key feature to constants is that they can not be changed during the execution of our code. To see this, let's try to change the variable.

package main

import "fmt"

func main() {
   const SIZE int = 10
   SIZE = 20
   fmt.Printf(SIZE)   
}

When we try to run this code, we will get the following error.

./main.go:10: cannot assign to SIZE