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).
A generic slice utility function in Go is a reusable tool that cuts out a specific section from any list of items, whether they are numbers, words, or custom objects. Think of it like a universal pair of scissors that works on any stack of papers without needing to know what's written on them. You use it whenever you need to grab a middle chunk of data without writing the same cutting logic for every different type of list.