How to Write a Generic Slice Utility Function in Go

Write a generic Go function using type parameters to slice any slice type safely and reuse the logic.

Use a generic function with a type parameter T to accept any slice type and return a new slice of the same type.

func Slice[T any](s []T, start, end int) []T {
	if start < 0 { start = 0 }
	if end > len(s) { end = len(s) }
	if start > end { start, end = end, start }
	return s[start:end]
}

Call it with any slice, like Slice[int](nums, 1, 3) or Slice[string](words, 0, 2).