Skip to content

Instantly share code, notes, and snippets.

@Kangaroux
Created April 19, 2022 00:06
Show Gist options
  • Save Kangaroux/4d33f16ad778215c4fd3d58e97df35b5 to your computer and use it in GitHub Desktop.
Save Kangaroux/4d33f16ad778215c4fd3d58e97df35b5 to your computer and use it in GitHub Desktop.
Golang: Generic pop function for slices
// 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