Skip to content

Commit d3707c8

Browse files
committed
refactor:Add check for nil Carbon and simplify Copy method
1 parent 64a9957 commit d3707c8

2 files changed

Lines changed: 25 additions & 15 deletions

File tree

carbon.go

Lines changed: 12 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -49,19 +49,16 @@ func NewCarbon(time ...StdTime) *Carbon {
4949
// Copy returns a new copy of the current Carbon instance
5050
// 复制 Carbon 实例
5151
func (c *Carbon) Copy() *Carbon {
52-
newCarbon := NewCarbon()
53-
54-
newCarbon.time = time.Date(c.Year(), time.Month(c.Month()), c.Day(), c.Hour(), c.Minute(), c.Second(), c.Nanosecond(), c.loc)
55-
newCarbon.layout = c.layout
56-
newCarbon.weekStartsAt = c.weekStartsAt
57-
newCarbon.weekendDays = c.weekendDays
58-
newCarbon.loc = c.loc
59-
newCarbon.Error = c.Error
60-
61-
newCarbon.lang.dir = c.lang.dir
62-
newCarbon.lang.locale = c.lang.locale
63-
newCarbon.lang.resources = c.lang.resources
64-
newCarbon.lang.Error = c.lang.Error
65-
66-
return newCarbon
52+
if c == nil {
53+
return nil
54+
}
55+
return &Carbon{
56+
layout: c.layout,
57+
time: time.Date(c.Year(), time.Month(c.Month()), c.Day(), c.Hour(), c.Minute(), c.Second(), c.Nanosecond(), c.loc),
58+
weekStartsAt: c.weekStartsAt,
59+
weekendDays: c.weekendDays,
60+
loc: c.loc,
61+
lang: c.lang.Copy(),
62+
Error: c.Error,
63+
}
6764
}

carbon_unit_test.go

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,19 @@ func TestNewCarbon(t *testing.T) {
3939
}
4040

4141
func TestCarbon_Copy(t *testing.T) {
42+
t.Run("nil carbon", func(t *testing.T) {
43+
oldCarbon := Now()
44+
oldCarbon = nil
45+
newCarbon := oldCarbon.Copy()
46+
47+
assert.Empty(t, oldCarbon.ToString())
48+
assert.Empty(t, newCarbon.ToString())
49+
50+
oldCarbon = oldCarbon.AddDay()
51+
assert.Empty(t, oldCarbon.ToString())
52+
assert.Empty(t, newCarbon.ToString())
53+
})
54+
4255
t.Run("copy time", func(t *testing.T) {
4356
oldCarbon := Parse("2020-08-05")
4457
newCarbon := oldCarbon.Copy()

0 commit comments

Comments
 (0)