Created
September 8, 2011 18:49
-
-
Save kylelemons/1204276 to your computer and use it in GitHub Desktop.
Enum types (bitshifted too)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"strings" | |
) | |
type foo int | |
const ( | |
One foo = iota | |
Two | |
Three | |
Four | |
) | |
var fooNames = [...]string{ | |
One: "One", | |
Two: "Two", | |
Three: "Three", | |
Four: "Four", | |
} | |
func (f foo) String() string { | |
return fooNames[f] | |
} | |
type mask int | |
const ( | |
Read mask = 1 << iota | |
Write | |
Async | |
) | |
var maskNames = [...]string{ | |
Read: "Read", | |
Write: "Write", | |
Async: "Async", | |
} | |
func (m mask) String() string { | |
var masks []string | |
for i := Read; i <= Async; i <<= 1 { | |
if m & i != 0 { | |
masks = append(masks, maskNames[i]) | |
} | |
} | |
return strings.Join(masks, " | ") | |
} | |
func main() { | |
for _, val := range []foo{One,Two,Three,Four} { | |
fmt.Printf("(%T) %v %v\n", val, int(val), val) | |
} | |
for _, val := range []mask{ | |
Read, | |
Write, | |
Async, | |
Read | Async, | |
Write | Async, | |
Read | Write, | |
Read | Write | Async, | |
} { | |
fmt.Printf("(%T) %v %v\n", val, int(val), val) | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(main.foo) 0 One | |
(main.foo) 1 Two | |
(main.foo) 2 Three | |
(main.foo) 3 Four | |
(main.mask) 1 Read | |
(main.mask) 2 Write | |
(main.mask) 4 Async | |
(main.mask) 5 Read | Async | |
(main.mask) 6 Write | Async | |
(main.mask) 3 Read | Write | |
(main.mask) 7 Read | Write | Async |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment