You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
This proposal is about adding a CloneFunc function to the slices package.
The signature of the function would be, func CloneFunc[S any, R any](s []S, f func(S) R) []R.
There are two motivations for such a function.
Creating a deep copy of a slice
Many structs have something like .Copy or .Clone or .DeepCopy to implement a deep copy mechanism. CloneFunc enables using the slices package to make a copy of slices of such structs by leaving the copy implementation up to the caller.
Creating a conversion of a slice
Often we'll have a struct of one type and wish to create a slice of another type based on the first one. For example, creating a []string of just the .Name field from a []Person. CloneFunc enables the caller to provide a conversion method when creating the new slice.
Related PR: #58865
This proposal is about adding a
CloneFunc
function to theslices
package.The signature of the function would be,
func CloneFunc[S any, R any](s []S, f func(S) R) []R
.There are two motivations for such a function.
Many structs have something like
.Copy
or.Clone
or.DeepCopy
to implement a deep copy mechanism.CloneFunc
enables using theslices
package to make a copy of slices of such structs by leaving the copy implementation up to the caller.Often we'll have a struct of one type and wish to create a slice of another type based on the first one. For example, creating a
[]string
of just the.Name
field from a[]Person
.CloneFunc
enables the caller to provide a conversion method when creating the new slice.I've worked with re-implementations of this function a few places, e.g.
https://github.com/hashicorp/nomad/blob/main/helper/funcs.go#L401-L410
https://github.com/shoenig/test/blob/main/internal/util/slices.go#L3-L10
The function is really about streamlining the monotonous implied for-loop. For example say we wish to deep copy,
The existing
slices
andmaps
package enable us to write something likeWith the addition of the proposed
CloneFunc
, this boils down toAnd for an example of using
CloneFunc
to convert a slice, say we have a slice ofand we want a slice of just the IDs from the original slice
With
CloneFunc
this becomesThe text was updated successfully, but these errors were encountered: