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)
	}
}
이 예제의 실행 버튼 만들기 코드 실행 결과
[1 2 5 8]
[Apple fig pear]
1. Leo (95)
2. Mia (82)
3. Zoe (82)
4. Ben (67)

연습

예제를 온라인 컴파일러에서 열고 값을 바꾸거나 한 줄을 추가한 다음, 실행하기 전에 출력을 예상해 보세요. 그런 다음 일부러 코드를 망가뜨리고 컴파일러 메시지를 읽어 보세요.

이 레슨을 마쳤나요?

학습 완료로 표시하면 진행 상황을 기록할 수 있습니다.

챌린지로 연습하기

이 레슨에서 배운 내용으로 실제 문제를 풀어 보세요. 모든 챌린지는 브라우저에서 실행되며 즉시 테스트와 AI 리뷰를 받을 수 있습니다.

모든 챌린지