-
Notifications
You must be signed in to change notification settings - Fork 3
/
example_test.go
75 lines (66 loc) · 1.45 KB
/
example_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package copy_test
import (
"fmt"
"github.com/liguangsheng/go-copy"
"github.com/modern-go/reflect2"
"time"
"unsafe"
)
// Example
func Example() {
var src = struct {
Field1 time.Time
Field2 int64
}{
Field1: time.Now(),
Field2: time.Now().Unix(),
}
var dest = struct {
Field1 int64
Field2 time.Time
}{}
if err := copy.Copy(&dest, src); err != nil {
fmt.Println(err)
}
}
// Example of custom handlers.
type IntToString struct{}
func (d *IntToString) Samples() (dest, src interface{}) {
return "", int(0)
}
func (d *IntToString) Copy(destType, srcType reflect2.Type, destPtr, srcPtr unsafe.Pointer) error {
val := *(srcType.PackEFace(srcPtr).(*int))
str := fmt.Sprintf("%d", val)
destType.UnsafeSet(destPtr, reflect2.PtrOf(str))
return nil
}
func ExampleHandler() {
var src int = 42
var dest string
copier := copy.New()
copier.Register(&IntToString{})
if err := copier.Copy(&dest, src); err != nil {
fmt.Println(err)
}
}
// Example of name function
func ExampleNameFunc() {
var src = struct {
Field1 int `copy:"copy_dest_field2"`
Field2 int `copy:"copy_dest_field1"`
}{
Field1: 111,
Field2: 222,
}
var dest struct {
Field1 int `copy:"copy_dest_field1"`
Field2 int `copy:"copy_dest_field2"`
}
copier := copy.New(copy.WithCacheSize(10000), copy.WithNameFunc(copy.NameByCopyTag))
if err := copier.Copy(&dest, src); err != nil {
fmt.Println(err)
} else {
fmt.Println(src) // {111 222}
fmt.Println(dest) // {222 111}
}
}