Created
August 1, 2014 07:01
-
-
Save elliots/38e63f26a70c5b71b989 to your computer and use it in GitHub Desktop.
Reading bit masks in golang using reflection
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 ( | |
"log" | |
"reflect" | |
"github.com/davecgh/go-spew/spew" | |
) | |
type MyImportantValues struct { | |
Hello bool | |
Goodbye bool | |
HowAreYou bool | |
_ bool | |
Something bool | |
_ bool | |
} | |
func main() { | |
spew.Dump("woo") | |
log.Print("hey") | |
mask := &MyImportantValues{} | |
readMask(123, mask) | |
spew.Dump("Read mask", mask) | |
} | |
func readMask(mask int, target interface{}) { | |
targetValue := reflect.Indirect(reflect.ValueOf(target)) | |
for i := 0; i < targetValue.NumField(); i++ { | |
value := (mask >> uint(i) & 1) > 0 | |
f := targetValue.Field(i) | |
if f.CanSet() { | |
targetValue.Field(i).SetBool(value) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment