2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Goのsortパッケージ

Last updated at Posted at 2020-06-04

sortパッケージ

基本的なソート

Intのスライスを昇順でソートする

items := []int{7, 2, 3, 1, 4, 5, 6}
sort.Ints(items)
fmt.Println(items)

[1 2 3 4 5 6 7]

Intのスライスを降順でソートする

items := []int{7, 2, 3, 1, 4, 5, 6}
sort.Sort(sort.Reverse(sort.IntSlice(items)))
fmt.Println(items)

[7 6 5 4 3 2 1]

Stringのスライスを昇順でソートする

items := []string{"c", "a", "b", "e", "d"}
sort.Strings(items)
fmt.Println(items)

[a b c d e]

Stringのスライスを降順でソートする

items := []string{"c", "a", "b", "e", "d"}
sort.Sort(sort.Reverse(sort.StringSlice(items)))
fmt.Println(items)

[e d c b a]

structのソート

  • スコアの昇順でソート
score := []struct {
	PlayerId int
	Score    int
}{
	{1, 50},
	{2, 20},
	{3, 100},
}
sort.Slice(score, func(i, j int) bool { return score[i].Score < score[j].Score })
fmt.Println(score)

[{2 20} {1 50} {3 100}]
2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?