-
Notifications
You must be signed in to change notification settings - Fork 2.1k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
fb429d6
commit e8ee087
Showing
1 changed file
with
42 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
package fn | ||
|
||
// Copyable is a generic interface for a type that's able to return a deep copy | ||
// of itself. | ||
type Copyable[T any] interface { | ||
Copy() T | ||
} | ||
|
||
// CopyAll creates a new slice where each item of the slice is a deep copy of | ||
// the elements of the input slice. | ||
func CopyAll[T Copyable[T]](xs []T) []T { | ||
newItems := make([]T, len(xs)) | ||
for i := range xs { | ||
newItems[i] = xs[i].Copy() | ||
} | ||
|
||
return newItems | ||
} | ||
|
||
// CopyableErr is a generic interface for a type that's able to return a deep copy | ||
// of itself. This is identical to Copyable, but should be used in cases where | ||
// the copy method can return an error. | ||
type CopyableErr[T any] interface { | ||
Copy() (T, error) | ||
} | ||
|
||
// CopyAllErr creates a new slice where each item of the slice is a deep copy of | ||
// the elements of the input slice. This is identical to CopyAll, but should be | ||
// used in cases where the copy method can return an error. | ||
func CopyAllErr[T CopyableErr[T]](xs []T) ([]T, error) { | ||
var err error | ||
|
||
newItems := make([]T, len(xs)) | ||
for i := range xs { | ||
newItems[i], err = xs[i].Copy() | ||
if err != nil { | ||
return nil, err | ||
} | ||
} | ||
|
||
return newItems, nil | ||
} |