refactor: 优化 slice 包中的 Copy 和 CopyMatrix 的函数签名和实现方式,不影响已有代码

This commit is contained in:
kercylan98 2023-12-29 14:11:20 +08:00
parent efbde3e3f8
commit cf42ed649a
1 changed files with 13 additions and 14 deletions

View File

@ -29,25 +29,24 @@ func Del[V any](slice *[]V, index int) {
} }
// Copy 复制特定切片 // Copy 复制特定切片
func Copy[V any](slice []V) []V { // - 该函数已经可使用标准库 slices.Clone 代替,但是由于调用者可能繁多,所以该函数将不会被移除
var s = make([]V, len(slice), len(slice)) func Copy[S ~[]V, V any](slice S) S {
for i := 0; i < len(slice); i++ { if slice == nil {
s[i] = slice[i] return nil
} }
return s return append(slice[:0:0], slice...)
} }
// CopyMatrix 复制二维数组 // CopyMatrix 复制二维数组
func CopyMatrix[V any](slice [][]V) [][]V { func CopyMatrix[S ~[][]V, V any](slice S) S {
var s = make([][]V, len(slice), len(slice)) if slice == nil {
return nil
}
var result = make(S, len(slice))
for i := 0; i < len(slice); i++ { for i := 0; i < len(slice); i++ {
is := make([]V, len(slice[0])) result[i] = Copy(slice[i])
for j := 0; j < len(slice[0]); j++ {
is[j] = slice[i][j]
} }
s[i] = is return result
}
return s
} }
// Insert 在特定索引插入元素 // Insert 在特定索引插入元素