diff --git a/micro/microfunctions.go b/micro/microfunctions.go index 78216aa7..22e5c1f5 100644 --- a/micro/microfunctions.go +++ b/micro/microfunctions.go @@ -3,7 +3,9 @@ package micro import ( + "bytes" "context" + "encoding/gob" "errors" "fmt" "hash/fnv" @@ -829,3 +831,13 @@ func StringFloat32_Dimension2(f float32) string { func ShowTimePassed(StartAt time.Time) { fmt.Print("Time passed: ", time.Since(StartAt)) } + +// StructDeepCopy - копирует структуру из src в dist +// dist - обязательно ссылка & +func StructDeepCopy(src, dist interface{}) (err error) { + buf := bytes.Buffer{} + if err = gob.NewEncoder(&buf).Encode(src); err != nil { + return + } + return gob.NewDecoder(&buf).Decode(dist) +} diff --git a/micro/microfunctions_test.go b/micro/microfunctions_test.go index 4d1901e2..1bff12ab 100644 --- a/micro/microfunctions_test.go +++ b/micro/microfunctions_test.go @@ -6,6 +6,7 @@ import ( "fmt" "github.com/ManyakRus/starter/contextmain" "os" + "reflect" "testing" "time" ) @@ -598,3 +599,38 @@ func TestStringFloat32_Dimension2(t *testing.T) { func TestShowTimePassed(t *testing.T) { defer ShowTimePassed(time.Now()) } + +func TestStructDeepCopy(t *testing.T) { + type NestedStruct struct { + Number int + Text string + } + + type TestStruct struct { + ID int + Name string + Nested NestedStruct + Numbers []int + } + + src := TestStruct{ + ID: 1, + Name: "Test", + Nested: NestedStruct{ + Number: 100, + Text: "Nested", + }, + Numbers: []int{1, 2, 3}, + } + + var dist TestStruct + + err := StructDeepCopy(src, &dist) + if err != nil { + t.Fatalf("error copying struct: %v", err) + } + + if !reflect.DeepEqual(src, dist) { + t.Errorf("copied struct does not match original struct") + } +}