In der Go-Sprache ist Slice leistungsfähiger, flexibler und bequemer als ein Array und eine leichtgewichtige Datenstruktur. Das Slice ist eine Sequenz variabler Länge, die Elemente eines ähnlichen Typs speichert, es ist Ihnen nicht erlaubt, unterschiedliche Typen von Elementen in demselben Slice zu speichern.
In der Go-Sprache können Sie ein Slice mit Hilfe der Funktion Slice() sortieren . Diese Funktion sortiert den angegebenen Slice unter Berücksichtigung der bereitgestellten Less-Funktion. Das Ergebnis dieser Funktion ist nicht stabil. Für eine stabile Sortierung können Sie also SliceStable verwenden. Und diese Funktion gerät in Panik, wenn die angegebene Schnittstelle nicht vom Slice-Typ ist. Es ist unter dem Sortierpaket definiert, sodass Sie das Sortierpaket in Ihr Programm importieren müssen, um auf die Slice-Funktion zugreifen zu können.

Syntax:

func Slice(a_slice interface{}, less func(p, q int) bool)

Beispiel:

// Go program to illustrate
// how to sort a slice
package main
  
import (
    "fmt"
    "sort"
)
  
// Main function
func main() {
  
    // Creating and initializing
    // a structure
    Author := []struct {
        a_name    string
        a_article int
        a_id      int
    }{
        {"Mina", 304, 1098},
        {"Cina", 634, 102},
        {"Tina", 104, 105},
        {"Rina", 10, 108},
        {"Sina", 234, 103},
        {"Vina", 237, 106},
        {"Rohit", 56, 107},
        {"Mohit", 300, 104},
        {"Riya", 4, 101},
        {"Sohit", 20, 110},
    }
  
    // Sorting Author by their name
    // Using Slice() function
    sort.Slice(Author, func(p, q int) bool { 
      return Author[p].a_name < Author[q].a_name })
      
    fmt.Println("Sort Author according to their names:")
    fmt.Println(Author)
  
    // Sorting Author by their
    // total number of articles
    // Using Slice() function
    sort.Slice(Author, func(p, q int) bool { 
       return Author[p].a_article < Author[q].a_article })
      
    fmt.Println()
    fmt.Println("Sort Author according to their"+
                    " total number of articles:")
      
    fmt.Println(Author)
  
    // Sorting Author by their ids
    // Using Slice() function
    sort.Slice(Author, func(p, q int) bool { 
     return Author[p].a_id < Author[q].a_id })
      
    fmt.Println()
    fmt.Println("Sort Author according to the their Ids:")
    fmt.Println(Author)
}

Ausgabe:

Autoren nach Namen sortieren:
[{Cina 634 102} {Mina 304 1098} {Mohit 300 104} {Rina 10 108} {Riya 4 101} {Rohit 56 107} {Sina 234 103} {Sohit 20 110} {Tina 104 105} {Vina 237 106}]

Sortieren Sie die Autoren nach der Gesamtzahl der Artikel:
[{Riya 4 101} {Rina 10 108} {Sohit 20 110} {Rohit 56 107} {Tina 104 105} {Sina 234 103} {Vina 237 106} {Mohit 300 104 } {Mina 304 1098} {Cina 634 102}]

Autor nach ID sortieren:
[{Riya 4 101} {Cina 634 102} {Sina 234 103} {Mohit 300 104} {Tina 104 105} {Vina 237 106} {Rohit 56 107} {Rina 10 108} { Sohit 20 110} {Mina 304 1098}]