Skip to content

Instantly share code, notes, and snippets.

@elliots
Created August 1, 2014 07:01
Show Gist options
  • Save elliots/38e63f26a70c5b71b989 to your computer and use it in GitHub Desktop.
Save elliots/38e63f26a70c5b71b989 to your computer and use it in GitHub Desktop.
Reading bit masks in golang using reflection
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