-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathapi_cloneable_test.go
50 lines (44 loc) · 1.14 KB
/
api_cloneable_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
package routine
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestCloneable(t *testing.T) {
//struct can not be cast to interface
var value any = personCloneable{Id: 1, Name: "Hello"}
_, ok := value.(Cloneable)
assert.False(t, ok)
//pointer can be cast to interface
var pointer any = &personCloneable{Id: 1, Name: "Hello"}
_, ok2 := pointer.(Cloneable)
assert.True(t, ok2)
//nil pointer can be cast to interface
pointer = (*personCloneable)(nil)
cloneable, ok3 := pointer.(Cloneable)
assert.True(t, ok3)
assert.True(t, cloneable != nil)
}
func TestCloneable_Clone(t *testing.T) {
//clone struct
pc := &personCloneable{Id: 1, Name: "Hello"}
assert.NotSame(t, pc, pc.Clone())
assert.Equal(t, *pc, *(pc.Clone().(*personCloneable)))
//copy pointer
pcs := make([]*personCloneable, 1)
pcs[0] = pc
pcs2 := make([]*personCloneable, 1)
copy(pcs2, pcs)
assert.Same(t, pc, pcs2[0])
//clone nil panic
assert.Panics(t, func() {
pc2 := (*personCloneable)(nil)
_ = pc2.Clone()
})
}
type personCloneable struct {
Id int
Name string
}
func (p *personCloneable) Clone() any {
return &personCloneable{Id: p.Id, Name: p.Name}
}