Skip to content

slices: add a CloneFunc function #58865

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions src/slices/slices.go
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,17 @@ func Clone[S ~[]E, E any](s S) S {
return append(S([]E{}), s...)
}

// CloneFunc creates a transposition of the slice using f to create each
// corresponding element. May be used for creating a deep copy of s by supplying
// an f that creates a deep copy of each element.
func CloneFunc[S any, R any](s []S, f func(S) R) []R {
r := make([]R, len(s))
for i := 0; i < len(s); i++ {
r[i] = f(s[i])
}
return r
}

// Compact replaces consecutive runs of equal elements with a single copy.
// This is like the uniq command found on Unix.
// Compact modifies the contents of the slice s; it does not create a new slice.
Expand Down
11 changes: 11 additions & 0 deletions src/slices/slices_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -351,6 +351,17 @@ func TestClone(t *testing.T) {
}
}

func TestCloneFunc(t *testing.T) {
s1 := []byte{65, 66, 67}
s2 := CloneFunc[byte, string](s1, func(c byte) string {
return string(c)
})
want := []string{"A", "B", "C"}
if !Equal(s2, want) {
t.Errorf("CloneFunc(%v) = %#v, want %#v", s1, s2, want)
}
}

var compactTests = []struct {
name string
s []int
Expand Down