Skip to content

Commit 8c9de4d

Browse files
authored
Merge pull request #9345 from ziggie1984/add-copy-method
Add a deep copy generic harness to the internal fn package
2 parents fb429d6 + e8ee087 commit 8c9de4d

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

fn/func.go

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
package fn
2+
3+
// Copyable is a generic interface for a type that's able to return a deep copy
4+
// of itself.
5+
type Copyable[T any] interface {
6+
Copy() T
7+
}
8+
9+
// CopyAll creates a new slice where each item of the slice is a deep copy of
10+
// the elements of the input slice.
11+
func CopyAll[T Copyable[T]](xs []T) []T {
12+
newItems := make([]T, len(xs))
13+
for i := range xs {
14+
newItems[i] = xs[i].Copy()
15+
}
16+
17+
return newItems
18+
}
19+
20+
// CopyableErr is a generic interface for a type that's able to return a deep copy
21+
// of itself. This is identical to Copyable, but should be used in cases where
22+
// the copy method can return an error.
23+
type CopyableErr[T any] interface {
24+
Copy() (T, error)
25+
}
26+
27+
// CopyAllErr creates a new slice where each item of the slice is a deep copy of
28+
// the elements of the input slice. This is identical to CopyAll, but should be
29+
// used in cases where the copy method can return an error.
30+
func CopyAllErr[T CopyableErr[T]](xs []T) ([]T, error) {
31+
var err error
32+
33+
newItems := make([]T, len(xs))
34+
for i := range xs {
35+
newItems[i], err = xs[i].Copy()
36+
if err != nil {
37+
return nil, err
38+
}
39+
}
40+
41+
return newItems, nil
42+
}

0 commit comments

Comments
 (0)