From 5b785f4a1947d6bb69389470b6b1663c4d1c9120 Mon Sep 17 00:00:00 2001 From: cya <2081215119@qq.com> Date: Thu, 30 May 2024 14:03:43 +0800 Subject: [PATCH] perf(slice): make a clearer panic description --- docs/api/packages/slice.md | 6 +++--- docs/en/api/packages/slice.md | 6 +++--- slice/slice.go | 27 +++++++++------------------ 3 files changed, 15 insertions(+), 24 deletions(-) diff --git a/docs/api/packages/slice.md b/docs/api/packages/slice.md index 8004227f..f8f3c751 100644 --- a/docs/api/packages/slice.md +++ b/docs/api/packages/slice.md @@ -322,12 +322,12 @@ func main() { ### Concat -

合并多个slices到slice中

+

创建一个新的切片,将传入的切片拼接起来返回。

函数签名: ```go -func Concat[T any](slice []T, slices ...[]T) []T +func Concat[T any](slices ...[]T) []T ``` 示例:[运行](https://go.dev/play/p/gPt-q7zr5mk) @@ -1542,7 +1542,7 @@ func main() { } ``` -### Merge +### Merge(废弃:使用Concat)

合并多个切片(不会消除重复元素).

diff --git a/docs/en/api/packages/slice.md b/docs/en/api/packages/slice.md index f8b38a0c..dc0a9643 100644 --- a/docs/en/api/packages/slice.md +++ b/docs/en/api/packages/slice.md @@ -321,12 +321,12 @@ func main() { ### Concat -

Creates a new slice concatenating slice with any additional slices.

+

Concat creates a new slice concatenating slice with any additional slices.

Signature: ```go -func Concat[T any](slice []T, slices ...[]T) []T +func Concat[T any](slices ...[]T) []T ``` Example:[Run](https://go.dev/play/p/gPt-q7zr5mk) @@ -1540,7 +1540,7 @@ func main() { } ``` -### Merge +### Merge(deprecated: use Concat)

Merge all given slices into one slice.

diff --git a/slice/slice.go b/slice/slice.go index 3c0066a6..13830a90 100644 --- a/slice/slice.go +++ b/slice/slice.go @@ -109,18 +109,18 @@ func Compact[T comparable](slice []T) []T { // Concat creates a new slice concatenating slice with any additional slices. // Play: https://go.dev/play/p/gPt-q7zr5mk -func Concat[T any](slice []T, slices ...[]T) []T { - totalLen := len(slice) - +func Concat[T any](slices ...[]T) []T { + totalLen := 0 for _, v := range slices { totalLen += len(v) + if totalLen < 0 { + panic("len out of range") + } } - result := make([]T, 0, totalLen) - result = append(result, slice...) - for _, s := range slices { - result = append(result, s...) + for _, v := range slices { + result = append(result, v...) } return result @@ -833,20 +833,11 @@ func UnionBy[T any, V comparable](predicate func(item T) V, slices ...[]T) []T { return result } +// Deprecated: Please use Concat() function instead. // Merge all given slices into one slice. // Play: https://go.dev/play/p/lbjFp784r9N func Merge[T any](slices ...[]T) []T { - totalLen := 0 - for _, v := range slices { - totalLen += len(v) - } - result := make([]T, 0, totalLen) - - for _, v := range slices { - result = append(result, v...) - } - - return result + return Concat(slices...) } // Intersection creates a slice of unique elements that included by all slices.