GoLang sorting structure slices
This article describes how to sort structure slices in Go.
GoLang sorting structure slices
GoLang provides two methods to sort a struct slice; one is sort.Slice
and the other is sort.SliceStable
. We also need to use the less function with these two methods to sort a struct slice.
The syntax for these methods is:
//sort.Slice
func Slice(x StructSlice, less func(i, j int) bool)
//sort.SliceStable
func Slice(x StructSlice, less func(i, j int) bool)
Where x is a slice of structure and the slice will be sorted according to the less function. Let us try to implement some examples to understand how to sort a slice of structure in GoLang.
Sort a struct slice by field
Sorting a struct slice by field is a basic example of sorting a struct slice. We compare the value of one member of a struct slice with the value of another member of the same struct slice based on a field, let's see an example.
package main
import (
"fmt"
"sort"
)
type Employee struct {
Name string
Salary int
}
func main() {
// Sort in Ascending order
employees := []Employee{
{Name: "John", Salary: 1500},
{Name: "Joe", Salary: 3000},
{Name: "Jack", Salary: 3400},
}
sort.Slice(employees, func(i, j int) bool {
return employees[i].Salary < employees[j].Salary
})
fmt.Println(employees)
// Sort in Descending order
employees1 := []Employee{
{Name: "John", Salary: 1500},
{Name: "Joe", Salary: 3000},
{Name: "Jack", Salary: 3400},
}
sort.Slice(employees1, func(i, j int) bool {
return employees1[i].Salary > employees1[j].Salary
})
fmt.Println(employees1)
}
The above code contains an Employee structure with two fields Name and Salary, then it creates a slice of the structure and sorts it in ascending order based on the field Salary using the Slice method, and then sorts another slice in descending order.
See the output:
[{John 1500} {Joe 3000} {Jack 3400}]
[{Jack 3400} {Joe 3000} {John 1500}]
Now we cannot use on these types of slices sort.SliceStable
which include key-value pairs (maps) of field names and values. Using sort.SliceStable
, we can sort simple slices of structures which contain only values.
package main
import (
"fmt"
"sort"
)
type Employee struct {
Name string
Salary int
}
func main() {
// Sort in Ascending order
employees := []Employee{
{"John", 1500},
{"Joe", 3000},
{"Jack", 3400},
}
sort.SliceStable(employees, func(i, j int) bool {
return employees[i].Salary < employees[j].Salary
})
fmt.Println(employees)
// Sort in Descending order
employees1 := []Employee{
{"John", 1500},
{"Joe", 3000},
{"Jack", 3400},
}
sort.SliceStable(employees1, func(i, j int) bool {
return employees1[i].Salary > employees1[j].Salary
})
fmt.Println(employees1)
}
The above code will similarly sort the struct slice based on the fields in the struct slice that do not have key-value pairs of name and value.
See the output:
[{John 1500} {Joe 3000} {Jack 3400}]
[{Jack 3400} {Joe 3000} {John 1500}]
Sort a struct slice by multiple fields
It is also possible to sort a slice of a structure by multiple fields. We have to extend the less function; let's take an example.
package main
import (
"fmt"
"sort"
)
type Employee struct {
Name string
Position string
}
func main() {
// Sort in Descending order
employees := []Employee{
{"Michael", "Developer"},
{"Jack", "Manager"},
{"Joe", "CEO"},
{"Leonard", "Intern"},
{"Sheldon", "Developer"},
}
sort.SliceStable(employees, func(i, j int) bool {
if employees[i].Position != employees[j].Position {
return employees[i].Position < employees[j].Position
}
return employees[i].Name < employees[j].Name
})
fmt.Println(employees)
// Sort in Ascending order
employees1 := []Employee{
{"Michael", "Developer"},
{"Jack", "Manager"},
{"Joe", "CEO"},
{"Leonard", "Intern"},
{"Sheldon", "Developer"},
}
sort.SliceStable(employees1, func(i, j int) bool {
if employees1[i].Position != employees1[j].Position {
return employees1[i].Position > employees1[j].Position
}
return employees1[i].Name > employees1[j].Name
})
fmt.Println(employees1)
}
The above code will sort based on Name and Position, if two employees have same position then it will sort based on Name field. Slices of structure will be sorted in descending and ascending order.
See the output:
[{Joe CEO} {Michael Developer} {Sheldon Developer} {Leonard Intern} {Jack Manager}]
[{Jack Manager} {Leonard Intern} {Sheldon Developer} {Michael Developer} {Joe CEO}]
For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.
Related Articles
Install GoLang using Brew
Publish Date:2025/04/15 Views:82 Category:Go
-
This article describes how to install GoLang using Brew on Linux or macOS. Install GoLang using Brew brew installs missing packages in Linux and macOS. It makes it easy to install GoLang on Linux or macOS. Follow the steps below to install
GoLang RWMutex Detailed Introduction
Publish Date:2025/04/15 Views:116 Category:Go
-
This article introduces how to use rwmutex in Go language. Go language RWMutex mutex is the abbreviation of mutual exclusion, which is used to keep track of which thread has accessed a variable at any time. Mutex is a data structure provide
Enabling CORS in GoLang
Publish Date:2025/04/15 Views:102 Category:Go
-
This article describes how to enable and use CORS in GoLang. Go language CORS Cross-origin resource sharing (CORS) is a process based on HTTP headers that defines the origins from which browsers are allowed to load and use resources. CORS i
Function pointers in Go
Publish Date:2025/04/15 Views:83 Category:Go
-
A pointer in Go is a special-purpose variable that stores the memory address of other variables and the point where the memory is located. It can also access the value stored in that memory location. Pointer declaration in Go var pointer_na
Duration in Go
Publish Date:2025/04/15 Views:89 Category:Go
-
Go duration conversion can be done in a variety of ways. The time library and the time.duration method are often used to calculate and display time. Note that duration refers to the time elapsed between two defined time objects, as an int64
Create a new directory in Go
Publish Date:2025/04/15 Views:112 Category:Go
-
Go has many ways to create directories, one of which is os.Mkdir . We can assign specified names and permission bits to the newly formed directory. os.MkdirAll Useful for recursively creating multiple directories, including any missing pare
How to read a file into a string in GoLang
Publish Date:2025/04/15 Views:90 Category:Go
-
The Go language provides a lot of file manipulation tools, one of which is how to read files into strings. ioutil.ReadFile() , File.Read() , buf.ReadFrom() and strings.Builder are just a few of the methods that can be used to efficiently wr
Declaring constant Map in Go
Publish Date:2025/04/15 Views:166 Category:Go
-
Map is a collection of key-value pairs which can be sorted in any order. It assigns values to keys. The keys in a Map are always unique, but the values are not always unique. The map data structure is used for fast key-based dat
Merge two maps in Golang
Publish Date:2025/04/15 Views:164 Category:Go
-
This article describes how to merge two maps in Golang. Golang does not provide any in-built functionality to merge mappings, but this can be achieved using Copy method or by following the corresponding procedure. Let’s try both the metho