Constants
fixed -unchanging- values
should be initialize with a value
const pi float64 = 3.14 // typed constant
const e = 2.71 // untyped constant
default value assignment grouped constants
const (
max1 = 1
max2
max3
)
fmt.Println(max1, max2, max3)
// 1 1 1
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")
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
Constant Expression
const somestr = "some" + "str"
const someBool = 5 < 7
initializing constant by
multiplying typed constants not works
const x int = 3
const y float64 = 2.1 * x // Not works
however it works with untyped constants
const x = 3
const y float64 = 2.1 * x // works
- 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
IOTA
constant increasing sequences
const (
m1 = iota
m2 = iota
m3 = iota
)
same with following
const (
m1 = iota
m2
m3
)
fmt.Println(m1, m2, m3)
// 0 1 2
multiply by 2
const (
m1 = iota * 2
m2
m3
)
fmt.Println(m1, m2, m3)
// 0 2 4
using blank identifier
const (
m1 = -iota - 3 // -3
_ // -4
m2 // -5
m3 // -6
)
fmt.Println(m1, m2, m3)
Top comments (0)