YouTip LogoYouTip

Go Constants

Constants are identifiers for simple values that cannot be modified during program execution. The data types in constants can only be boolean, numeric (integer, floating-point, and complex), and string.

Word Explanation: const is an abbreviation for constant, representing an immutable value in a program.


Basic Syntax and Parameters

The format for defining a constant:

const identifier  = value

Syntax Explanation

  • identifier: The name of the constant, following Go identifier naming rules (letters, digits, underscores, and cannot start with a digit).
  • type (optional): The type name. If omitted, the compiler will infer it automatically.
  • value: The value of the constant.

Definition Methods

  • Explicit type definition: const b string = "abc"
  • Implicit type definition: const b = "abc"
  • Batch definition: const c_name1, c_name2 = value1, value2

Examples

Example 1: Basic Constant Definition

Example

package main

import "fmt"

func main() {
    const LENGTH int = 10
    const WIDTH int = 5
    var area int
    const a, b, c = 1, false, "str" // Multiple assignment
    area = LENGTH * WIDTH
    fmt.Printf("Area: %d", area)
    println()
    println(a, b, c)
}

Expected Output:

Area: 50
1 false str

Code Explanation:

  1. const LENGTH int = 10 defines an integer constant LENGTH with a value of 10.
  2. const WIDTH int = 5 defines an integer constant WIDTH with a value of 5.
  3. const a, b, c = 1, false, "str" uses multiple assignment to define several constants of different types simultaneously.
  4. area = LENGTH * WIDTH calculates the area and assigns it to the variable area.

Constant Groups and Enumerations

Go does not have an enum keyword. Constant groups are typically used to achieve enumeration effects:

Example

package main

import "fmt"

// Define gender enumeration
const (
    Unknown = 0
    Female  = 1
    Male    = 2
)

func main() {
    fmt.Printf("Unknown=%d, Female=%d, Male=%d\n", Unknown, Female, Male)
}

Expected Output:

Unknown=0, Female=1, Male=2

Code Explanation:

  • Using a constant group allows you to define a set of related constant values.
  • The numbers 0, 1, and 2 represent unknown gender, female, and male, respectively.

Application of Built-in Functions in Constants

Built-in functions like len(), cap(), and unsafe.Sizeof() can be used in constant expressions to compute values.

Note: Functions in constant expressions must be built-in functions.

Example

package main

import (
    "fmt"
    "unsafe"
)

const (
    a = "abc"
    b = len(a)
    c = unsafe.Sizeof(a)
)

func main() {
    fmt.Printf("a=%s, b=%d, c=%d\n", a, b, c)
}

Expected Output:

a=abc, b=3, c=16

Code Explanation:

  • a = "abc": A string constant.
  • b = len(a): Uses len() to get the string length, resulting in 3.
  • c = unsafe.Sizeof(a): Uses unsafe.Sizeof() to get the memory size of the variable, resulting in 16 bytes (the string struct occupies 16 bytes on a 64-bit system).

The iota Constant Counter

iota is a special constant in Go, also known as a constant counter. It can automatically generate incrementing sequence values within a const declaration block.

Key Features:

  • iota is reset to 0 when the const keyword appears.
  • For each new constant declaration line in a const block, iota automatically increments by 1.
  • It can be thought of as the line index within a const block (starting from 0).

Example 1: Basic iota Usage

Example

package main

import "fmt"

// iota starts at 0 and increments by 1 for each line
const (
    a = iota // 0
    b        // 1 (value omitted, defaults to the previous line's iota)
    c        // 2
)

func main() {
    fmt.Printf("a=%d, b=%d, c=%d\n", a, b, c)
}

Expected Output:

a=0, b=1, c=2

Code Explanation:

  • When a constant value is omitted, it defaults to the previous line's iota value.
  • Therefore, b=1, c=2.

Example 2: Detailed iota Usage

Example

package main

import "fmt"

func main() {
    const (
        a = iota // 0
        b        // 1
        c        // 2
        d = "ha" // Independent value, iota += 1
        e        // "ha", iota += 1
        f = 100  // Independent value, iota += 1
        g        // 100, iota += 1
        h = iota // 7, resumes using the iota value
        i        // 8
    )
    fmt.Printf("a=%d, b=%d, c=%d, d=%s, e=%s, f=%d, g=%d, h=%d, i=%d\n", a, b, c, d, e, f, g, h, i)
}

Expected Output:

a=0, b=1, c=2, d=ha, e=ha, f=100, g=100, h=7, i=8

Code Explanation:

  • When an explicit assignment is made, that value is used, but iota still increments.
  • When an assignment is omitted, the value from the previous line is used.
  • At h = iota, it resumes using the current value of iota (7).

Example 3: iota with Bit Shifting

Example

package main

import "fmt"

const (
    i = 1 << iota // 1 << 0 = 1
    j = 3 << iota // 3 << 1 = 6
    k             // 3 << 2 = 12
    l             // 3 << 3 = 24
)

func main() {
    fmt.Printf("i=%d, j=%d, k=%d, l=%d\n", i, j, k, l)
}

Expected Output:

i=1, j=6, k=12, l=24

Code Explanation:

  • << is the left shift operator. x << n is equivalent to x * 2^n.
  • i = 1 << 0 = 1: 1 shifted left by 0 bits, result is 1.
  • j = 3 << 1 = 6: 3 shifted left by 1 bit, binary 11 becomes 110, which is 6.
  • k = 3 << 2 = 12: 3 shifted left by 2 bits, binary 11 becomes 1100, which is 12.
  • l = 3 << 3 = 24: 3 shifted left by 3 bits, binary 11 becomes 11000, which is 24.

Additional Notes

  • 1 << n = 1 * 2^n
  • 3 << n = 3 * 2^n
← Python3 List OperatorPython3 Month Days β†’