File tree Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments