Created
April 19, 2022 00:06
-
-
Save Kangaroux/4d33f16ad778215c4fd3d58e97df35b5 to your computer and use it in GitHub Desktop.
Golang: Generic pop function for slices
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
// SlicePop pops an element from a slice and returns the new slice and element. | |
// | |
// SlicePop modifies the slice. To preserve the original slice, make a copy. | |
// | |
// arr := []int{1, 2, 3} | |
// arr, elem := SlicePop(arr, 1) | |
// fmt.Println(arr, elem) // [1 3] 2 | |
func SlicePop[T any](s []T, i int) ([]T, T) { | |
elem := s[i] | |
s = append(s[:i], s[i+1:]...) | |
return s, elem | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment