Skip to content

Instantly share code, notes, and snippets.

@dyerw
Created November 3, 2014 04:54
Show Gist options
  • Save dyerw/c89d8c3728e3ce480a46 to your computer and use it in GitHub Desktop.
Save dyerw/c89d8c3728e3ce480a46 to your computer and use it in GitHub Desktop.
A bunch of reflective nonsense in go, but a good example
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