What is the easiest way to sort a slice of structs by an arbitrary field in Go?
Hi everyone! I'm new to Go and can't figure out how to sort slices of structs. Let's say I have this code:\n\n```go\ntype Person struct {\n Name string\n Age int\n}\n\npeople := []Person{\n {"Alice", 30},\n {"Bob", 25},\n {"Charlie", 35},\n}\n```\n\nI want to sort this slice by the `Name` field (alphabetically). Then, possibly by the `Age` field (ascending). In other languages (e.g., Python), I would just pass a sort key: `sorted(people, key=lambda p: p.name)`. But in Go, I see that I need to write a separate type, implement the `sort.Interface` with three methods — `Len()`, `Less()`, `Swap()`. This is very verbose!\n\nIs there a shorter and more elegant way to do this? Maybe some built-in function or package that allows
No answers yet.
Log in to leave an answer