Skip to content

Commit

Permalink
给slice和map增加none的判定
Browse files Browse the repository at this point in the history
  • Loading branch information
yangyile committed Dec 12, 2024
1 parent fea23ee commit 0b68b88
Show file tree
Hide file tree
Showing 4 changed files with 32 additions and 0 deletions.
8 changes: 8 additions & 0 deletions mustmap/must_map.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,14 @@ func Nice[K comparable, V any](a map[K]V) map[K]V {
return a
}

// None ensures the map is empty, panics if not.
// None 确保 map 内容为空,若有元素则 panic。
func None[K comparable, V any](a map[K]V) {
if len(a) != 0 {
zaplog.ZAPS.P1.LOG.Panic("expect LENGTH = 0 while contains elements")
}
}

// Length checks if the length of a map is equal to n. If not, it panics.
// Length 检查一个 map 的长度是否等于 n,如果不等,则触发 panic。
func Length[K comparable, V any](a map[K]V, n int) {
Expand Down
8 changes: 8 additions & 0 deletions mustmap/must_map_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,14 @@ func TestNice(t *testing.T) {
})
}

func TestNone(t *testing.T) {
mustmap.None(map[int]int{})

tests.ExpectPanic(t, func() {
mustmap.None(map[string]int{"a": 1, "b": 2})
})
}

func TestLength(t *testing.T) {
// 正常情况: map 的长度等于期望值
mustmap.Length(map[int]string{
Expand Down
8 changes: 8 additions & 0 deletions mustslice/must_slice.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,14 @@ func Nice[T any](a []T) []T {
return a
}

// None ensures the slice is empty, panics if not.
// None 确保切片内容为空,若有元素则 panic。
func None[T any](a []T) {
if len(a) != 0 {
zaplog.ZAPS.P1.LOG.Panic("expect LENGTH = 0 while contains elements")
}
}

// Length checks if the slice's length equals the expected value, panics if not.
// Length 检查切片的长度是否等于期望值,不等则触发 panic。
func Length[T any](a []T, n int) {
Expand Down
8 changes: 8 additions & 0 deletions mustslice/must_slice_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,14 @@ func TestNice(t *testing.T) {
})
}

func TestNone(t *testing.T) {
mustslice.None([]int{})

tests.ExpectPanic(t, func() {
mustslice.None([]int{1, 2, 3})
})
}

func TestHave(t *testing.T) {
// 非空切片通过
mustslice.Have([]int{1, 2, 3})
Expand Down

0 comments on commit 0b68b88

Please sign in to comment.