Sort Slice of Structures in Golang

Create new folder named entities. In entities folder, create new file named product.go as below:

package entities

type Product struct {
	Id       string
	Name     string
	Price    float64
	Quantity int
	Status   bool
}

Create new folder named src. In src folder, create new file named main.go as below:

package main

import (
	"entities"
	"fmt"
	"sort"
)

func main() {
	var products = []entities.Product{
		entities.Product{
			Id:       "p01",
			Name:     "tivi 1",
			Price:    5,
			Quantity: 9,
			Status:   false,
		},
		entities.Product{
			Id:       "p02",
			Name:     "tivi 2",
			Price:    2,
			Quantity: 8,
			Status:   true,
		},
		entities.Product{
			Id:       "p03",
			Name:     "laptop 3",
			Price:    11,
			Quantity: 7,
			Status:   false,
		},
	}

	fmt.Println("Sort Product ASC")
	SortASC(products)
	for _, product := range products {
		Display(product)
		fmt.Println("-------------------------")
	}

	fmt.Println("Sort Product DESC")
	SortDESC(products)
	for _, product := range products {
		Display(product)
		fmt.Println("-------------------------")
	}

}

func SortDESC(products []entities.Product) {
	sort.Slice(products, func(i, j int) bool {
		return products[i].Price > products[j].Price
	})
}

func SortASC(products []entities.Product) {
	sort.Slice(products, func(i, j int) bool {
		return products[i].Price < products[j].Price
	})
}

func Display(product entities.Product) {
	fmt.Println("id: ", product.Id)
	fmt.Println("name: ", product.Name)
	fmt.Println("price: ", product.Price)
	fmt.Println("quantity: ", product.Quantity)
	fmt.Println("status: ", product.Status)
	fmt.Println("total: ", (product.Price * float64(product.Quantity)))
}




Open Terminal windows in Visual Studio Code and run command line: go run main.go

Sort Product ASC
id:  p02
name:  tivi 2
price:  2
quantity:  8
status:  true
total:  16
-------------------------
id:  p01
name:  tivi 1
price:  5
quantity:  9
status:  false
total:  45
-------------------------
id:  p03
name:  laptop 3
price:  11
quantity:  7
status:  false
total:  77
-------------------------

Sort Product DESC
id:  p03
name:  laptop 3
price:  11
quantity:  7
status:  false
total:  77
-------------------------
id:  p01
name:  tivi 1
price:  5
quantity:  9
status:  false
total:  45
-------------------------
id:  p02
name:  tivi 2
price:  2
quantity:  8
status:  true
total:  16
-------------------------