Sujets Go importants
Sorting in Go: sort and slices
Sort numbers, strings and structs, and write your own order with a comparison function.
Ce que vous allez apprendre
- sort.Ints
- slices.SortFunc
- sort.Slice for structs
Ranking
Leo95
Mia82
Zoe82
Ben67
You decide the order
Go sorts slices in place. sort.Ints and sort.Strings cover the simple cases, and sort.Slice or slices.SortFunc take a function that decides the order.
slices.SortFunc compares two items and returns a negative number, zero or a positive number; comparing the lower-case forms ignores capital letters. sort.Slice takes a function that says whether item i comes before item j: here a higher score first, then the name.
Points clés
- Sorting changes the slice in place.
sort.Slicetakes a less function.- Break ties with a second comparison.
Exemple Go exécutable
main.go
package main
import (
"fmt"
"slices"
"sort"
"strings"
)
type Student struct {
Name string
Score int
}
func main() {
numbers := []int{5, 2, 8, 1}
sort.Ints(numbers)
fmt.Println(numbers)
words := []string{"pear", "Apple", "fig"}
slices.SortFunc(words, func(a, b string) int {
return strings.Compare(strings.ToLower(a), strings.ToLower(b))
})
fmt.Println(words)
students := []Student{{"Mia", 82}, {"Leo", 95}, {"Zoe", 82}, {"Ben", 67}}
sort.Slice(students, func(i, j int) bool {
if students[i].Score != students[j].Score {
return students[i].Score > students[j].Score
}
return students[i].Name < students[j].Name
})
for rank, student := range students {
fmt.Printf("%d. %s (%d)\n", rank+1, student.Name, student.Score)
}
}
[1 2 5 8]
[Apple fig pear]
1. Leo (95)
2. Mia (82)
3. Zoe (82)
4. Ben (67)S'entraîner
Ouvrez l'exemple dans le compilateur en ligne, modifiez une valeur ou ajoutez une ligne, et devinez la sortie avant de l'exécuter. Cassez ensuite le code exprès et lisez le message du compilateur.
Leçon terminée ?
Marquez-la comme apprise pour suivre votre progression.
Votre progression est enregistrée dans ce navigateur Connectez-vous pour la garder sur tous vos appareils.
S'entraîner avec un défi
Utilisez le contenu de cette leçon pour résoudre un vrai problème. Chaque défi s'exécute dans le navigateur, avec des tests instantanés et une revue par l'IA.
Tous les défis