Go Constants Fundamentals

GolangGolangBeginner
Practice Now

Introduction

In the previous lessons, we learned about variables in Go. In this lesson, we will explore the concept of constants, how to use them, and why they are important. Let's dive into 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/BasicsGroup -.-> go/values("Values") go/BasicsGroup -.-> go/constants("Constants") go/BasicsGroup -.-> go/variables("Variables") subgraph Lab Skills go/values -.-> lab-149070{{"Go Constants Fundamentals"}} go/constants -.-> lab-149070{{"Go Constants Fundamentals"}} go/variables -.-> 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 you 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
const labex string = "LabEx" // explicitly specify the type as string
const labs = "LABS"    // automatically inferred as string by the compiler

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

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

    fmt.Println()

    fmt.Println(hangzhou, chengdu)
    fmt.Println(monday, tuesday, wednesday)
}
go run ~/project/const.go

After running the program, the output is as follows:

The type of labex is: string, and its value is LabEx
The type of labs is: string, and its value is LABS

HANGZHOU CHENGDU
MONDAY TUESDAY 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, it will inherit the previous constant's value.

Enter the following code in const.go:

package main

import "fmt"

const (
    monday    = "MONDAY"
    tuesday   = "TUESDAY"
    wednesday = "WEDNESDAY"
    thursday
    friday
)

func main() {
    fmt.Println(monday, tuesday, wednesday, thursday, friday)
}
go run ~/project/const.go

The output is as follows:

MONDAY TUESDAY WEDNESDAY WEDNESDAY WEDNESDAY

Here, thursday and friday do not have explicit values. According to Go's rules, when a constant is not explicitly initialized, it inherits the value of the previous constant. In this case:

  • thursday inherits the value of wednesday.
  • friday also inherits the value of wednesday.

This behavior allows for concise code but can lead to unexpected results if you are not aware of it.

If you want thursday and friday to have distinct values, you need to explicitly assign them:

const (
    monday    = "MONDAY"
    tuesday   = "TUESDAY"
    wednesday = "WEDNESDAY"
    thursday  = "THURSDAY"
    friday    = "FRIDAY"
)

This will produce the expected output:

MONDAY TUESDAY WEDNESDAY THURSDAY FRIDAY

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
    tuesday   = iota // increments by 1 each time
    wednesday = iota
    thursday  = iota
    friday    = iota
)

func main() {
    fmt.Println(monday, tuesday, wednesday, thursday, friday)
}
go run ~/project/const.go

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
    tuesday          // 1
    wednesday        // 2
    thursday         // 3
    friday           // 4
)

func main() {
    fmt.Println(monday, tuesday, 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
    tuesday        // 1
    _
    thursday // 3
    friday   // 4
)

func main() {
    fmt.Println(monday, tuesday, thursday, friday)
}
go run ~/project/const.go

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)
}
go run ~/project/const.go

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 have 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.