Skip to content

Commit b3b6db8

Browse files
author
Dmitriy Matrenichev
committed
fix: fix Copy documentation and implementation
Copy should not create slices bigger than original. Fixed that. Signed-off-by: Dmitriy Matrenichev <[email protected]>
1 parent 521f737 commit b3b6db8

File tree

1 file changed

+5
-1
lines changed

1 file changed

+5
-1
lines changed

slices/slices.go

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -148,12 +148,16 @@ func Contains[T any](s []T, fn func(T) bool) bool {
148148
return IndexFunc(s, fn) >= 0
149149
}
150150

151-
// Copy returns a slice of V with the last n elements removed.
151+
// Copy copies first n elements. If n is greater than the length of the slice, it will copy the whole slice.
152152
func Copy[S ~[]V, V any](s S, n int) S {
153153
if s == nil {
154154
return nil
155155
}
156156

157+
if n > len(s) {
158+
n = len(s)
159+
}
160+
157161
result := make([]V, n)
158162
copy(result, s)
159163

0 commit comments

Comments
 (0)