...

/

Utilizing Go Constants

Utilizing Go Constants

Understand constants in Go, how to declare them, and their uses.

Constants provide values that are set at compile time and cannot change. This is in contrast to variables, which store values that can be set at runtime and can be altered. This provides types that cannot accidentally be changed by a user and are allocated for use in the software on startup, providing some speed advantages and safety over variable declarations.

Constants can be used to store the following:

  • Booleans

  • Runes

  • Integer types (int, int8, uint16, and so on)

  • Floating-point types (float32/float64)

  • Complex data types

  • Strings

In this lesson, we will discuss how to declare constants and use them in our code.

Declaring a constant

Constants are declared using the const keyword, as illustrated in the following code snippet:

Press + to interact
const str = "hello world"
const num = 3
const num int64 = 3

Constants are different from variable types in that they come in two flavors, as follows: ...