From b50855855b580b7c1ccc70d0faa519240d82b2ce Mon Sep 17 00:00:00 2001 From: Vasiliy Tolstov Date: Sun, 20 Dec 2020 00:15:29 +0300 Subject: [PATCH] config: export method to init new empty struct Signed-off-by: Vasiliy Tolstov --- config/reflect.go | 20 +++++++++++++++++++- config/reflect_test.go | 26 ++++++++++++++++++++++++++ 2 files changed, 45 insertions(+), 1 deletion(-) create mode 100644 config/reflect_test.go diff --git a/config/reflect.go b/config/reflect.go index dfc408ff..fd84a62b 100644 --- a/config/reflect.go +++ b/config/reflect.go @@ -1,6 +1,8 @@ package config -import "reflect" +import ( + "reflect" +) func IsEmpty(v reflect.Value) bool { switch v.Kind() { @@ -26,3 +28,19 @@ func IsEmpty(v reflect.Value) bool { } return false } + +func Zero(src interface{}) (interface{}, error) { + sv := reflect.ValueOf(src) + + if sv.Kind() == reflect.Ptr { + sv = sv.Elem() + } + + if sv.Kind() == reflect.Invalid { + return nil, ErrInvalidStruct + } + + dst := reflect.New(sv.Type()) + + return dst.Interface(), nil +} diff --git a/config/reflect_test.go b/config/reflect_test.go new file mode 100644 index 00000000..dd77533d --- /dev/null +++ b/config/reflect_test.go @@ -0,0 +1,26 @@ +package config_test + +import ( + "testing" + + "github.com/unistack-org/micro/v3/config" +) + +type Config struct { + Value string + SubConfig *SubConfig + Config *Config +} + +type SubConfig struct { + Value string +} + +func TestReflect(t *testing.T) { + cfg1 := &Config{Value: "cfg1", Config: &Config{Value: "cfg1_1"}, SubConfig: &SubConfig{Value: "cfg1"}} + cfg2, err := config.Clone(cfg1) + if err != nil { + t.Fatal(err) + } + t.Logf("dst: %#+v\n", cfg2) +}