How do I partition a slice of structs in Go?

In Go, you can partition a slice of structs using a custom function that separates the elements based on a specified condition. This is useful when you want to categorize or filter data efficiently. Below is an example demonstrating how to partition a slice of structs based on a specific field.

package main import ( "fmt" ) type Person struct { Name string Age int } // Partition function separates the slice based on a condition func Partition(people []Person, ageLimit int) ([]Person, []Person) { var young []Person var old []Person for _, person := range people { if person.Age < ageLimit { young = append(young, person) } else { old = append(old, person) } } return young, old } func main() { people := []Person{ {"Alice", 22}, {"Bob", 34}, {"Charlie", 18}, {"David", 45}, } young, old := Partition(people, 30) fmt.Printf("Young: %v\n", young) fmt.Printf("Old: %v\n", old) }

Go Slice Structs Partition Data Handling