Created
November 3, 2014 04:54
-
-
Save dyerw/c89d8c3728e3ce480a46 to your computer and use it in GitHub Desktop.
A bunch of reflective nonsense in go, but a good example
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" | |
"reflect" | |
) | |
type Example struct { | |
A string | |
B string | |
C string | |
} | |
type AnotherExample struct { | |
D string | |
E string | |
F string | |
} | |
func main() { | |
ex := Example{C: "bar"} | |
SetDefaults(&ex) | |
fmt.Printf("%#v\n", ex) | |
anex := AnotherExample{D: "bar", E: "foo"} | |
SetDefaults(&anex) | |
fmt.Printf("%#v\n", anex) | |
} | |
// Changes every empty string field to ".*" | |
func SetDefaults(ex interface{}) { | |
v := reflect.ValueOf(ex).Elem() | |
for i := 0; i < v.NumField(); i++ { | |
f := v.Field(i) | |
if s, ok := f.Interface().(string); ok && s == "" { | |
f.Set(reflect.ValueOf(".*")) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment