DEV Community

indiewebdev
indiewebdev

Posted on

Golang Notes - 5

Constants

fixed -unchanging- values

should be initialize with a value

const pi float64 = 3.14 // typed constant
const e = 2.71 // untyped constant
Enter fullscreen mode Exit fullscreen mode

default value assignment grouped constants

const (
    max1 = 1
    max2
    max3
)
fmt.Println(max1, max2, max3)
// 1 1 1
Enter fullscreen mode Exit fullscreen mode

Constant Rules

  • can not change after initialization
  • can not initialize at runtime

const x = math.Pow(2,3)

however can use builtin function available at compile time

const lenH = len("h")
Enter fullscreen mode Exit fullscreen mode

string literals unnamed constants
Unnamed constants are all boolean, numeric and string values.

  • can not use variable to initialize
s := 3
const S = s // not works
Enter fullscreen mode Exit fullscreen mode

Constant Expression

const somestr = "some" + "str"
const someBool = 5 < 7
Enter fullscreen mode Exit fullscreen mode

initializing constant by
multiplying typed constants not works

const x int = 3
const y float64 = 2.1 * x  // Not works
Enter fullscreen mode Exit fullscreen mode

however it works with untyped constants

const x = 3
const y float64 = 2.1 * x  // works
Enter fullscreen mode Exit fullscreen mode
  • can not declare constants of type array ONLY boolean constants, rune constants, integer constants, floating-point constants, complex constants, and string constants.
const x = [2]int{1, 2} // not valid
const y [2]int = {4, 3} // not valid
Enter fullscreen mode Exit fullscreen mode

IOTA

constant increasing sequences

const (
    m1 = iota
    m2 = iota
    m3 = iota
)
Enter fullscreen mode Exit fullscreen mode

same with following

const (
    m1 = iota
    m2
    m3
)

fmt.Println(m1, m2, m3)
// 0 1 2
Enter fullscreen mode Exit fullscreen mode

multiply by 2

const (
    m1 = iota * 2
    m2
    m3
)

fmt.Println(m1, m2, m3)
// 0 2 4
Enter fullscreen mode Exit fullscreen mode

using blank identifier

const (
        m1 = -iota - 3 // -3
        _  // -4
        m2 // -5
        m3 // -6
)

fmt.Println(m1, m2, m3)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)