Skip to content

Commit

Permalink
fn: add deep copy interface.
Browse files Browse the repository at this point in the history
  • Loading branch information
ziggie1984 committed Dec 10, 2024
1 parent fb429d6 commit e8ee087
Showing 1 changed file with 42 additions and 0 deletions.
42 changes: 42 additions & 0 deletions fn/func.go
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
}

0 comments on commit e8ee087

Please sign in to comment.