← All Exercises

Go Custom Slice Sorting

intermediatego~15min

Background

Go sort package provides flexible sorting through custom less functions and the sort.Interface.

Problem

Write a Go function that sorts a slice of Person structs by age (ascending), then by name (ascending) for ties.

Input

A slice of Person structs with Name and Age fields.

Output

The slice sorted by age, then name for equal ages.

Sample tests

Sample 1

Input: [{Bob,30},{Alice,25},{Carol,30}]
Expected: [{Alice,25},{Bob,30},{Carol,30}]

Your solution

Learning objective

Learn sort.Slice with custom comparators and multi-criteria sorting logic.