Go Constants


Constants in Go represent immutable values determined at compile time. They can be of various basic types like integers, floating-point numbers, characters, strings, and booleans. Unlike variables, constants cannot be changed after they are declared.

package main

import "fmt"

const (
	Pi       = 3.14159
	Language = "Go"
	Truth    = true
)

func main() {
	fmt.Println("Value of Pi:", Pi)
	fmt.Println("Language:", Language)
	fmt.Println("Is it true?", Truth)

	// The following line would result in a compile-time error
	// because you cannot modify a constant:
	// Pi = 3.14

	// Typed constants
	const typedInt int = 10
	fmt.Println("Typed constant:", typedInt)


	// Untyped constants
	const untypedFloat = 20.5
	var float32Var float32 = float32(untypedFloat)
	var float64Var float64 = untypedFloat
	fmt.Println("Untyped constant as float32:", float32Var)
	fmt.Println("Untyped constant as float64:", float64Var)
}

This code snippet demonstrates a few key aspects of constants:

Using constants makes your code more readable, maintainable, and less prone to errors by providing named values that won’t accidentally be modified during program execution. They are particularly useful for defining values that have a special meaning or are used repeatedly throughout your code.