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)
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?