Constants in Go

Intro

Constants are declared like variables, but with the const keyword. Constants can only be character, string, boolean, or numeric values and cannot be declared using the := syntax. An untyped constant takes the type needed by its context.

Example:

const Pi = 3.14
const (
        StatusOK                   = 200
        StatusCreated              = 201
        StatusAccepted             = 202
        StatusNonAuthoritativeInfo = 203
        StatusNoContent            = 204
        StatusResetContent         = 205
        StatusPartialContent       = 206
)
  • Constants belong to compile time. They must be initilized with value when they are declared.

  • Constants are created at compile time. In the run time, Go just transforms it into a value.

  • Unnamed constants: All basic literals are unnamed constants. Following are examples of basic literals:

    // Unnamed constants
    1
    3.14
    "hello"
    true
    false
    
  • Named Constants: All named constants will be replaced to their values in runtime. They need to be declared first.

  • Untyped Constants: Constants may or may not have a type.

  • If the value is’nt going to change throughout our program’s lifetime and we already know the value (if it belongs to compile time) then we should go for named constants.

  • Constants are immutable i.e. we cannot change their values.

  • We cannot initialize a constant to a runtime value.

  • We can use expressions while initializing constants.

Constant Types

  • We can declare constants using non-numeric types as well.

  • Constants don’t have to be only numeric values.

  • We don't have to declare the types of constants.

  • For e.g.

    func main() {
        // Below works..
        const min       int     = 1
        const pi        float64 = 3.14
        const version   string  = "2.0.3"
        const debug     bool    = true
    
        // Declaring constants without types also works.
        const min     = 1
        const pi      = 3.14
        const version = "2.0.3"
        const debug   = true
    
        // We can use expressions while initializing constants.
        const min     = 1 + 1               //2
        const pi      = 3.14 * min          // 6.28
        const version = "2.0.3" + "-beta"   // 2.0.3-beta
        const debug   = !true               // false
    }
    

Multiple Constants Declaration

  • Constants get their types and expressions from the previous constant.

  • We can declare multiple constants in a single go as below:

    func main() {
        // Multiple constants of same type in one go
        const min, max int = 1, 1000
    
        // Declaring in group
        const (
            min int = 1
            max int = 1000
        )
    
        // Constants get their types and expressions from the previous constant
        const (
            min int = 1000     // 1000
            max                // 1000
        )
    }
    

Typeless Or Untyped Constants

  • When we declare a constant without a type, it becomes untyped constant (typeless constant).

  • All basic literals are also typeless. They all are typeless constant values.

  • A constant with a type can only be used with a value of the same type.

  • The untyped numeric constant can be used with all numeric values together.

  • For e.g.

    func main() {
        const min = 42
    
        var i int      =  min  // Type of constant 'min' = int
        var f float64  =  min  // Type of constant 'min' = float64
        var b byte     =  min  // Type of constant 'min' = byte
        var j int32    =  min  // Type of constant 'min' = int32
        var r rune     =  min  // Type of constant 'min' = rune
    }
    

Default Types

  • Conversion only happens when a type is needed.

  • Go converts a typeless constant to a typed value when a type is needed.

  • For e.g.

    func main() {
        const min int32 = 1000
    
        max := 5 + min // Type of 'max' is 'int32'
                       // Internally this happens: max := int32(5) + min
    }
    
  • Go implicitly converts the typeless constant to a typed value.

  • For e.g.

    func main() {
        const min = 1000
    
        max := 5 + min // Type of 'max' is 'int'
                       // Internally this happens: max := int(5) + int(min)
    }
    
  • An untyped constant has a default type.

  • Go evaluates the expression then it converts the resulting typeless value to its default value.

IOTA

  • IOTA is nothing but a number generator for constants. In other words, it is ever increasing automatic counter.

  • IOTA is built-in constant generator which generates ever increasing numbers.

  • IOTA starts at 0.

  • We can use expressions with IOTA. So, the other constants will repeat the expressions.

  • We can use blank identifier (_) to adjust the values of constants:

    func main() {
        const (
            EST = -(5 + iota)   // -5
            _                   // -6 | Discarded/skipped due to blank identifier
            MST                 // -7
            PST                 // -8
        )
    }
    

See also