1
0
mirror of https://github.com/ManyakRus/starter.git synced 2025-11-27 23:18:34 +02:00

сделал StructDeepCopy()

This commit is contained in:
Nikitin Aleksandr
2024-04-10 13:12:11 +03:00
parent 719f80ab2b
commit 5cfb8cbc93
2 changed files with 48 additions and 0 deletions

View File

@@ -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)
}

View File

@@ -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")
}
}