Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,895 questions

51,826 answers

573 users

How to sort a slice of structs by multiple columns in Go

1 Answer

0 votes
package main

import (
    "fmt"
    "sort"
)

type Item struct {
    A     int
    B     int
    Label string
}

// Print method
func (i Item) String() string {
    return fmt.Sprintf("(%d, %d, %s)", i.A, i.B, i.Label)
}

// Sort by A, then B
func sortData(items []Item) {
    sort.Slice(items, func(i, j int) bool {
        if items[i].A != items[j].A {
            return items[i].A < items[j].A
        }
        return items[i].B < items[j].B
    })
}

// Print all items
func printData(items []Item) {
    for _, item := range items {
        fmt.Println(item)
    }
}

// Find first item by label
func findByLabel(items []Item, label string) *Item {
    for _, item := range items {
        if item.Label == label {
            return &item
        }
    }
    return nil
}

// Filter by A
func filterByA(items []Item, value int) []Item {
    var result []Item
    for _, item := range items {
        if item.A == value {
            result = append(result, item)
        }
    }
    return result
}

func main() {
    // data
    data := []Item{
        {7, 2, "python"},
        {8, 3, "c"},
        {3, 5, "c++"},
        {4, 1, "c#"},
        {3, 2, "java"},
        {7, 1, "go"},
        {1, 2, "rust"},
    }

    // Work on a copy so original stays unchanged
    items := append([]Item(nil), data...)

    sortData(items)
    fmt.Println("Sorted data:")
    printData(items)

    fmt.Println("\nSearching for 'java':")
    if found := findByLabel(items, "java"); found != nil {
        fmt.Println(found)
    }

    fmt.Println("\nFiltering items where A == 7:")
    filtered := filterByA(items, 7)
    printData(filtered)
}



/*
run:

Sorted data:
(1, 2, rust)
(3, 2, java)
(3, 5, c++)
(4, 1, c#)
(7, 1, go)
(7, 2, python)
(8, 3, c)

Searching for 'java':
(3, 2, java)

Filtering items where A == 7:
(7, 1, go)
(7, 2, python)

*/

 



answered Jan 29 by avibootz
...