11# Introduction
22
3- Constants are variables that are set to a value at compile time and cannot be reassigned.
4- Use the ` const ` keyword to declare a constant:
3+ Constants are values set at compile time and cannot be reassigned.
4+ Use the ` const ` keyword to declare a single constant:
55
66``` go
77const greeting = " hello"
88```
99
1010Multiple constants can be declared in a block.
11- Within a block, a constant without an explicit value repeats the previous expression:
11+ Within a block, a constant without an explicit value set repeats the previous expression:
1212
1313``` go
1414const (
@@ -18,12 +18,12 @@ const (
1818)
1919```
2020
21- Constants are typically declared at package level, though they can also be declared inside a function.
21+ Constants are typically declared at package level, though uncommonly they can also be declared inside a function.
2222
2323## Typed and untyped constants
2424
2525Declaring a constant without specifying a type makes it untyped.
26- An untyped constant has no set type; its value determines what types it's compatible with.
26+ An untyped constant has no set type, but its value determines what types it's compatible with.
2727As long as the underlying value is compatible, the compiler will convert it to the required type at each use:
2828
2929``` go
@@ -43,7 +43,7 @@ math.Sqrt(num) // compile error because a float is expected
4343
4444## What can be a constant
4545
46- Constants can only hold booleans , numbers, strings, and runes.
46+ Constants can only hold Booleans , numbers, strings, and runes.
4747Because the values are set at compile time, the results of a function call can not be constants:
4848
4949``` go
@@ -64,3 +64,19 @@ const (
6464```
6565
6666Each constant after the first inherits the same expression, with ` iota ` incrementing by one.
67+
68+ ` iota ` also works in expressions.
69+
70+ ``` go
71+ const (
72+ _ = iota // position 0: value discarded
73+ KB = 1 << (10 * iota ) // position 1: 1 << 10 = 1024
74+ MB // position 2: 1 << 20 = 1048576
75+ GB // position 3: 1 << 30 = 1073741824
76+ )
77+ ```
78+
79+ For a deeper look at constants in Go, see [ The Go Blog] [ const-blog ] and [ Effective Go] [ effective-go ] .
80+
81+ [ const-blog ] : https://go.dev/blog/constants
82+ [ effective-go ] : https://go.dev/doc/effective_go#constants
0 commit comments