Go Basics

Go Constants

Description

Constants are declared like variables, but with the `const` keyword. Constants can be character, string, boolean, or numeric values. They cannot be declared using the `:=` syntax.

Pros & Cons

✅ Pros

  • Immutability: Prevents accidental changes.
  • Optimization: Compiler handles constants efficiently.

❌ Cons

  • Fixed: Value must be known at compile time.

When to Use

Defining configuration values, math constants (Pi), or enums.

Example

Using untyped and typed constants.

const Pi = 3.14

const (
    StatusOk = 200
    StatusNotFound = 404
)

func main() {
    const World = "世界"
    fmt.Println("Hello", World)
    fmt.Println("Pi:", Pi)
}

Best Practices

Use `iota` for creating enumerated constants (enums).

← Go VariablesGo Output →