1
0
Fork 0

Add duplicate function

This commit is contained in:
Gregory Eremin 2015-08-29 12:55:18 +03:00
parent 601ec4e86d
commit 27bb46973f
2 changed files with 22 additions and 0 deletions

View File

@ -27,3 +27,16 @@ func unmarshal(body []byte, target interface{}) error {
return nil return nil
} }
func duplicate(original interface{}) interface{} {
// Get the interface value
val := reflect.ValueOf(original)
// We expect a pointer to a struct, so now we need the underlying staruct
val = reflect.Indirect(val)
// Now we need the type (name) of this struct
typ := val.Type()
// Creating a duplicate instance of that struct
dupe := reflect.New(typ).Interface()
return dupe
}

View File

@ -42,3 +42,12 @@ func TestUnmarshal(t *testing.T) {
t.Errorf("Expected Bar to equal %q, got %q", 1, conf.Bar) t.Errorf("Expected Bar to equal %q, got %q", 1, conf.Bar)
} }
} }
func TestDuplicate(t *testing.T) {
var i interface{} = &testConf{}
dupe := duplicate(i)
if _, ok := dupe.(*testConf); !ok {
t.Error("Duplication failed")
}
}