Go: Define Constants

Go: Define Constants

Β·

2 min read

In Go it is good to use constants instead of regular variables to define identifiers for values that will not change during program execution. We use the keyword "const" to define constants.

package main

import "fmt"

// global public constant
const Pi = 3.14

func main() {
    //local string constant
    const world = "δΈ–η•Œ"
    fmt.Println("Hello", world)
    fmt.Println("Happy", Pi, "Day")

    //local Boolean constant
    const truth = true
    fmt.Println("Go rules?", truth)
}

Try it: https://go.dev/play/p/9mY4cwCCbDP

Notes:


Constants can be global or local. Usually global constants start with capital letters to be public. Local constants make sense to define with lowercase, but you can also use uppercase letters.

  • Constants are declared with the const keyword.

  • Constants can be character, string, boolean, or numeric values.

  • Constants must be initialized with literal using the assign symbol "=".


Explained by Rix

Constants in Go are declared using the const keyword. They are similar to variables, except that their value cannot be changed after declaration.

Constants are useful for:

  • Declaring literal values that never change - like mathematical constants, configuration values, etc.

  • Making code more readable by giving meaningful names to magic values.

  • Catching typos and errors at compile time rather than runtime.

Good practices when using constants:

  • Use meaningful constant names that describe their purpose.

  • Use ALL_CAPS for constant names as a convention to distinguish them from variables.

  • Avoid reassigning constants. It will generate a compile error.

Some use cases of constants in Go:

  • Mathematical constants - const pi = 3.14

  • Config values - const dbHost = "localhost"

  • Status codes - const statusOK = 200

  • Maximum/minimum values - const maxUsers = 100

  • Default values - const defaultLimit = 25

  • Enumerations - const ( Monday = 1 Tuesday = 2 Wednesday = 3)

Constants are evaluated at compile time in Go, so they have no runtime cost. This makes constants an efficient and type-safe alternative to "magic strings/numbers" in your code.


If you are getting older, increase the speed! πŸ––πŸΌπŸ€

Β