Skip to content

Sort a Slice of Structs by a Field in Go

Sorting a slice in golang is easy and the “sort” package is your friend.

Sort package has a Slice() method:

func Slice(x any, less func(i, j int) bool)

In this code example, we are sorting the slice of users according to their Age field:

package main

import (
	"fmt"
	"sort"
)

type User struct {
	Name string
	Age  int
}

func main() {
	users := []User{
		{Name: "Jack", Age: 30},
		{Name: "Morteza", Age: 20},
		{Name: "Sara", Age: 40},
	}

	sort.Slice(users, func(i, j int) bool {
		return users[i].Age < users[j].Age // use ">" if you want descending order
	})

	fmt.Println(users)
}
Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *