Last active
December 28, 2023 16:02
-
-
Save lezhnev74/d0523697ca165e49bdcc32b4f84a0569 to your computer and use it in GitHub Desktop.
Go slices lib
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
// slicePutAt is an efficient insertion function that avoid unnecessary allocations | |
func slicePutAt[V any](dst []V, pos int, v V) []V { | |
dst = append(dst, v) // could grow here | |
copy(dst[pos+1:], dst[pos:]) | |
dst[pos] = v | |
return dst | |
} | |
// sliceFilterInPlace does not allocate | |
func sliceFilterInPlace[T any](input []T, filter func(elem T) bool) []T { | |
n := 0 | |
for _, elem := range input { | |
if filter(elem) { | |
input[n] = elem | |
n++ | |
} | |
} | |
return input[:n] | |
} | |
// sliceSortUnique removes duplicates in place, returns sorted values | |
// also see slices.Compact | |
func sliceSortUnique[V constraints.Ordered](s []V) []V { | |
slices.Sort(s) | |
if len(s) == 0 { | |
return s | |
} | |
k := 1 | |
for i := 1; i < len(s); i++ { | |
if s[i] != s[k-1] { | |
s[k] = s[i] | |
k++ | |
} | |
} | |
return s[:k] | |
} | |
// SliceToAny converts any type to any | |
func SliceToAny[T any](in []T) (ret []any) { | |
ret = make([]any, len(in)) | |
for i, v := range in { | |
ret[i] = v | |
} | |
return | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment