Go Example: Constants

1. Introduction

Constants in Go are fixed values that are declared and cannot be altered by the program during execution. They are defined using the const keyword and can be character, string, boolean, or numeric values. This blog post will explore the use of constants in Go.

2. Program Steps

1. Declare constants using the const keyword.

2. Attempt to use these constants in various operations.

3. Print out the constants and results of these operations.

3. Code Program

package main

import (
	"fmt"
	"math"
)

// Enumerated constants using iota
const (
	n1 = iota
	n2
	n3
)

func main() {
	// Step 1: Declare constants
	const pi = 3.14
	const s string = "constant"

	// Step 2: Use constants in operations
	fmt.Println("pi:", pi)
	fmt.Println("string:", s)

	// Constant expressions perform arithmetic with arbitrary precision
	const n = 500000000
	const d = 3e20 / n
	fmt.Println("d:", d)

	// A numeric constant has no type until it's given one, such as by an explicit conversion
	fmt.Println("sin(pi):", math.Sin(pi))

	// Step 3: Print out enumerated constants
	fmt.Println("n1, n2, n3:", n1, n2, n3)
}

Output:

pi: 3.14
string: constant
d: 600000000000
sin(pi): 0.0015926529164868282
n1, n2, n3: 0 1 2

Explanation:

1. package main - The package declaration for the Go program.

2. import "fmt" and import "math" - Importing the format and math packages for output and mathematical functions.

3. pi and s are constants defined at the package level, which can be used anywhere within this package.

4. const is used to declare a single constant (pi) and a group of enumerated constants (n1, n2, n3) using the iota enumerator.

5. fmt.Println is used to print constants and results of operations. Constant pi is used within the math.Sin function to demonstrate that constants can be involved in calculations with other values.

6. d shows that constant expressions can use high-precision arithmetic in Go.

7. n1, n2, and n3 are printed out, showcasing how iota provides simple enumerated constants in Go.

8. The output verifies the declared constants and the results of their operations, as expected in Go.


Comments