-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathmodel_example_test.go
112 lines (97 loc) · 2.44 KB
/
model_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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
// Copyright (c) Jeevanandam M. (https://github.com/jeevatkm).
// go-model source code and usage is governed by a MIT style
// license that can be found in the LICENSE file.
package model
import (
"fmt"
"reflect"
"strconv"
)
//
// Examples
//
// Register a custom `Converter` to allow conversions from `int` to `string`.
func ExampleAddConversion() {
AddConversion((*int)(nil), (*string)(nil), func(in reflect.Value) (reflect.Value, error) {
return reflect.ValueOf(strconv.FormatInt(in.Int(), 10)), nil
})
type StructA struct {
Mixed string
}
type StructB struct {
Mixed int
}
src := StructB{Mixed: 123}
dst := StructA{}
errs := Copy(&dst, &src)
if errs != nil {
panic(errs)
}
fmt.Printf("%v", dst)
// Output: {123}
}
// Register a custom `Converter` to allow conversions from `*int` to `string`.
func ExampleAddConversion_sourcePointer() {
AddConversion((**int)(nil), (*string)(nil), func(in reflect.Value) (reflect.Value, error) {
return reflect.ValueOf(strconv.FormatInt(in.Elem().Int(), 10)), nil
})
type StructA struct {
Mixed string
}
type StructB struct {
Mixed *int
}
val := 123
src := StructB{Mixed: &val}
dst := StructA{}
errs := Copy(&dst, &src)
if errs != nil {
panic(errs[0])
}
fmt.Printf("%v", dst)
// Output: {123}
}
// Register a custom `Converter` to allow conversions from `int` to `*string`.
func ExampleAddConversion_destinationPointer() {
AddConversion((*int)(nil), (**string)(nil), func(in reflect.Value) (reflect.Value, error) {
str := strconv.FormatInt(in.Int(), 10)
return reflect.ValueOf(&str), nil
})
type StructA struct {
Mixed *string
}
type StructB struct {
Mixed int
}
src := StructB{Mixed: 123}
dst := StructA{}
errs := Copy(&dst, &src)
if errs != nil {
panic(errs[0])
}
fmt.Printf("%v", *dst.Mixed)
// Output: 123
}
// Register a custom `Converter` to allow conversions from `int` to `*string` by passing types.
func ExampleAddConversion_destinationPointerByType() {
srcType := reflect.TypeOf((*int)(nil)).Elem()
targetType := reflect.TypeOf((**string)(nil)).Elem()
AddConversionByType(srcType, targetType, func(in reflect.Value) (reflect.Value, error) {
str := strconv.FormatInt(in.Int(), 10)
return reflect.ValueOf(&str), nil
})
type StructA struct {
Mixed *string
}
type StructB struct {
Mixed int
}
src := StructB{Mixed: 123}
dst := StructA{}
errs := Copy(&dst, &src)
if errs != nil {
panic(errs[0])
}
fmt.Printf("%v", *dst.Mixed)
// Output: 123
}