Go Constants Fundamentals

GolangGolangBeginner
Practice Now

Introduction

In the previous lessons, we learned about variables in Go. In this lesson, we will delve into what constants are, how to use them, and why they are important. Let's enter the world of constants.

Knowledge Points:

  • What are constants
  • Declaring constants
  • The iota constant generator
  • Using constants

Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL go(("`Golang`")) -.-> go/BasicsGroup(["`Basics`"]) go(("`Golang`")) -.-> go/FunctionsandControlFlowGroup(["`Functions and Control Flow`"]) go(("`Golang`")) -.-> go/DataTypesandStructuresGroup(["`Data Types and Structures`"]) go(("`Golang`")) -.-> go/ObjectOrientedProgrammingGroup(["`Object-Oriented Programming`"]) go/BasicsGroup -.-> go/constants("`Constants`") go/FunctionsandControlFlowGroup -.-> go/functions("`Functions`") go/DataTypesandStructuresGroup -.-> go/pointers("`Pointers`") go/DataTypesandStructuresGroup -.-> go/strings("`Strings`") go/ObjectOrientedProgrammingGroup -.-> go/struct_embedding("`Struct Embedding`") subgraph Lab Skills go/constants -.-> lab-149070{{"`Go Constants Fundamentals`"}} go/functions -.-> lab-149070{{"`Go Constants Fundamentals`"}} go/pointers -.-> lab-149070{{"`Go Constants Fundamentals`"}} go/strings -.-> lab-149070{{"`Go Constants Fundamentals`"}} go/struct_embedding -.-> lab-149070{{"`Go Constants Fundamentals`"}} end

What are Constants?

In simple terms, a constant is a value that is declared and cannot be modified during program execution. Constants allow the compiler to know their values before program execution, during the compilation phase.

Constant declarations can have specific values assigned to them. Their syntax is similar to that of variables, but once a constant value is declared, it cannot be changed.

Constants are useful when we want to declare a value that should not change, such as a website address or a specific meaningful value like π.

Declaring Constants

The declaration of constants is similar to that of variables. The keyword var is replaced with the keyword const.

Note: Constants must be assigned a value when declared.

In Go, all variables must be used after they are defined, but constants are an exception. Even if they are not used, there will be no error.

The syntax for declaring a constant is as follows:

const name [type] = value

name is the name of the constant being declared. type is the data type of the constant, but it can be omitted because Go can infer it automatically. The value at the end is the value assigned to the constant.

Note that only the following types can be used for constant declarations:

  • Integer types
  • Floating-point types
  • Complex types
  • Boolean types
  • String types

Let's look at an example. Create a new file called const.go in the ~/project directory:

touch ~/project/const.go

Enter the following code in const.go:

package main

import "fmt"

// Declare a single constant labex
const labex string = "LabEx" // explicitly specify the type as string
const shiyanlou = "SHIYANLOU"    // automatically inferred as string by the compiler

// Declare multiple constants
const hangzhou, chengdu = "HANGZHOU", "CHENGDU"
const (
    monday    = "MONDAY"
    thesday   = "THESDAY"
    wednesday = "WEDNESDAY"
)

func main() {
    fmt.Printf("The type of labex is: %T, and its value is %s\n", labex, labex)
    fmt.Printf("The type of shiyanlou is: %T, and its value is %s\n", shiyanlou, shiyanlou)

    fmt.Println()

    fmt.Println(hangzhou, chengdu)
    fmt.Println(monday, thesday, wednesday)
}

After running the program, the output is as follows:

The type of labex is: string, and its value is LabEx
The type of shiyanlou is: string, and its value is SHIYANLOU

HANGZHOU CHENGDU
MONDAY THESDAY WEDNESDAY

Here, we demonstrate the declaration of single and multiple constants. When declaring multiple constants, it is recommended to use parentheses.

In the program, we only demonstrate the declaration of string constants. However, constants can also have other types, such as integers and booleans.

When declaring multiple constants using parentheses, if a constant is not initialized, its value will be the same as the value on the previous line.

Enter the following code in const.go:

package main

import "fmt"

const (
    monday    = "MONDAY"
    thesday   = "THESDAY"
    wednesday = "WEDNESDAY"
    thursday
    friday
)

func main() {
    fmt.Println(monday, thesday, wednesday, thursday, friday)
}

The output is as follows:

MONDAY THESDAY WEDNESDAY WEDNESDAY WEDNESDAY

As you can see, the constants thursday and friday were declared without specific values and their output is the same as the previous constant, "WEDNESDAY".

The iota Constant Generator

In addition to declaring constants one by one, we can also use iota to declare them in batches. Let's look at an example. Write the following code in the const.go file:

package main

import "fmt"

const (
    monday    = iota // initial value is 0
    thesday   = iota // increments by 1 each time
    wednesday = iota
    thursday  = iota
    friday    = iota
)

func main() {
    fmt.Println(monday, thesday, wednesday, thursday, friday)
}

The output is as follows:

0 1 2 3 4

When using iota, the initial value is 0 and it increments by 1 for each subsequent item.

After the first item is declared, subsequent constants do not need to be assigned using iota. The following code will also run correctly:

package main

import "fmt"

const (
    monday    = iota // 0
    thesday          // 1
    wednesday        // 2
    thursday         // 3
    friday           // 4
)

func main() {
    fmt.Println(monday, thesday, wednesday, thursday, friday)
}

What if we want to skip a specific value? In this case, we can use an underscore. The following code skips the constant for Wednesday:

package main

import "fmt"

const (
    monday  = iota // 0
    thesday        // 1
    _
    thursday // 3
    friday   // 4
)

func main() {
    fmt.Println(monday, thesday, thursday, friday)
}

As you can see, the output is as follows:

0 1 3 4

The iota operator can also be used for arithmetic operations. Enter the following code in const.go:

package main

import "fmt"

const (
    a = iota     // 0
    b = iota * 3 // 1 * 3
    c = iota + 4 // 2 + 4
)

const (
    B  = 1 << (iota * 10) // equals 1 << (0 * 10)
    KB                    // 1024
    MB                    // 1048576
)

func main() {
    fmt.Println(a, b, c)
    fmt.Println(B, KB, MB)
}

The output is as follows:

0 3 6
1 1024 1048576

In the first batch of constant declarations, we use iota to perform simple arithmetic operations.

In the second batch, we use iota with the left shift operator << to express the values of 1 KB and 1 MB in terms of B. For example, 1 KB is equal to 1024B, and 1 MB is equal to 1024 * 1024, which is 1048576B.

Quiz

Now let's reinforce what we have learned. Create a new file called iota.go and use iota and constants to output the values of 1GB and 1TB in terms of B.

Requirements:

  1. Do not directly output the converted numbers. Use iota for conversion.
  2. The iota.go file should be located in the ~/project directory.

Hint: You can refer to the code in the "iota" section.

The required output format is as follows:

1GB is equal to 1073741824B
1TB is equal to 1099511627776B
âœĻ Check Solution and Practice

Summary

Let's review what we learned in this lesson:

  • Constants cannot be modified after they are declared.
  • Constants can be declared using the const keyword.
  • When declaring multiple constants, it is preferred to use parentheses.
  • The iota constant generator can be used for enumerating declarations.
  • iota can also be used in arithmetic operations.

In this lesson, we learned about constants and also introduced the iota constant generator. Strings, integers, floating-point numbers, and constants are the basic data types in Go.

Starting from the next lesson, we will learn about more complex advanced data types, such as arrays, slices, and maps.

Other Golang Tutorials you may like