หัวข้อสำคัญของ Go

Sorting in Go: sort and slices

Sort numbers, strings and structs, and write your own order with a comparison function.

  • ระดับกลาง
  • อ่าน 4 นาที
  • ตัวอย่างที่รันได้ 1 ตัวอย่าง
สิ่งที่คุณจะได้เรียนรู้
  • sort.Ints
  • slices.SortFunc
  • sort.Slice for structs
Ranking
Leo95
Mia82
Zoe82
Ben67
Mia comes before Zoe because the scores are equal.

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.

ประเด็นสำคัญ

  1. Sorting changes the slice in place.
  2. sort.Slice takes a less function.
  3. Break ties with a second comparison.

ตัวอย่าง Go ที่รันได้

Go
รันโค้ด →
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)
	}
}
สร้างปุ่ม Run สำหรับตัวอย่างนี้ ผลลัพธ์จากการรันโค้ด
[1 2 5 8]
[Apple fig pear]
1. Leo (95)
2. Mia (82)
3. Zoe (82)
4. Ben (67)

ฝึกฝน

เปิดตัวอย่างในคอมไพเลอร์ออนไลน์ ลองเปลี่ยนค่าหรือเพิ่มบรรทัด แล้วทายผลลัพธ์ก่อนกดรัน จากนั้นลองทำให้โค้ดผิดโดยตั้งใจ แล้วอ่านข้อความจากคอมไพเลอร์

เรียนบทนี้จบแล้วใช่ไหม

ทำเครื่องหมายว่าเรียนแล้วเพื่อติดตามความคืบหน้า

ถัดไป: Runes, Bytes and strings.Builder →

ฝึกด้วยโจทย์

ใช้สิ่งที่เรียนในบทนี้แก้ปัญหาจริง ทุกโจทย์รันในเบราว์เซอร์ พร้อมการทดสอบทันทีและรีวิวจาก AI

โจทย์ทั้งหมด