Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 49eb0d1

Browse files
authored
Add struct ptr (#11)
* dst有指针类型结构体 * fix
1 parent 821d2da commit 49eb0d1

3 files changed

Lines changed: 52 additions & 3 deletions

File tree

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
# Binaries for programs and plugins
2+
/cover.cov
23
*swp
34
*~
45
*.exe

deepcopy.go

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -201,9 +201,22 @@ func (d *deepCopy) checkCycle(sField reflect.Value) error {
201201
func (d *deepCopy) cpyStruct(dst, src reflect.Value, depth int) error {
202202

203203
if dst.Kind() != src.Kind() {
204-
if dst.Kind() == reflect.Ptr && !dst.IsNil() {
205-
dst = dst.Elem()
206-
return d.cpyStruct(dst, src, depth)
204+
if dst.Kind() == reflect.Ptr {
205+
// 不是空指针,直接解引用
206+
if !dst.IsNil() {
207+
return d.cpyStruct(dst.Elem(), src, depth)
208+
}
209+
210+
// 被拷贝结构体是指针类型,值是空,
211+
// 并且dst可以被设置值
212+
// 直接malloc一块内存
213+
if dst.Type().Elem().Kind() == reflect.Struct {
214+
if dst.CanSet() {
215+
p := reflect.New(dst.Type().Elem())
216+
dst.Set(p)
217+
return d.cpyStruct(dst.Elem(), src, depth)
218+
}
219+
}
207220
}
208221
return nil
209222
}

deepcopy_dst_ptr_struct_test.go

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package deepcopy
2+
3+
import (
4+
"testing"
5+
6+
"github.com/stretchr/testify/assert"
7+
)
8+
9+
type TestDstStructPtr_Dst struct {
10+
TestDstPtr *struct {
11+
X int
12+
Y int
13+
}
14+
}
15+
16+
type TestDstPtr2 struct {
17+
X int
18+
Y int
19+
}
20+
21+
type TestDstStructPtr_Src struct {
22+
TestDstPtr TestDstPtr2
23+
}
24+
25+
func Test_DstPtr_Struct(t *testing.T) {
26+
var dst TestDstStructPtr_Dst
27+
src := TestDstStructPtr_Src{
28+
TestDstPtr: TestDstPtr2{X: 3, Y: 4},
29+
}
30+
31+
Copy(&dst, &src).Do()
32+
assert.NotNil(t, dst.TestDstPtr)
33+
assert.Equal(t, dst.TestDstPtr.X, 3)
34+
assert.Equal(t, dst.TestDstPtr.Y, 4)
35+
}

0 commit comments

Comments
 (0)