Skip to content

Commit cfae07a

Browse files
committed
Addeded
1 parent 7ea7e12 commit cfae07a

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

golang-constants-enums.md

+48
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
Title: Golang: Constants, enums and iota
2+
Tags: golang
3+
4+
You can type or untype your constants. And untyped constant can be used in any expression and converted implicitly:
5+
6+
const thing = 5 // untyped
7+
const thing2 int = 5 // typed - only used in int expressions
8+
9+
Enums come by putting a bunch of consts in parens:
10+
11+
const (
12+
One = 1
13+
Two = 2
14+
Three = 4
15+
)
16+
17+
You can use iota to create these values. Within a const group, it starts at 1, and then increments for each expression.
18+
19+
const (
20+
One = 1 << iota // 1 (i.e. 1 << 1)
21+
Two // 2 (i.e. 1 << 2)
22+
Three // 4 (i.e 1 << 3)
23+
)
24+
25+
If you print a Two, for example, it will display 2.
26+
27+
You can 1) Give the enum a custom type and 2) give the custom type a String() method to change that:
28+
29+
Giving custom types methods is the OOP of golang. And will be discussed in later posts.
30+
31+
type Type int
32+
33+
const (
34+
One Type = 1 << iota // 1
35+
Two Type // 2 (i.e. 1 << 2)
36+
Three Type // 4 (i.e 1 << 3)
37+
)
38+
39+
func (t Type) String() string {
40+
s:=""
41+
if t&One==One {
42+
s+="One"
43+
}
44+
...
45+
return s
46+
}
47+
48+
Now if you print the 'One' type it will out the text "One".

0 commit comments

Comments
 (0)