Golang 筆記
  • Introduction
  • 安裝Golang
    • 本地編譯與安裝第三方套件
    • 第一個 GO 程式
    • export 與 import
    • 使用 go mod
  • 基本工具
  • DataBase操作
    • MySQL
    • 使用 ORM
    • MongoDB
  • 基本語法
    • Variable
    • BSON
    • JSON
    • 時間相關
    • Interface
    • Error
    • 型別
    • 字串
    • defer
    • panic, recover
    • Channel 與Goroutine
      • 讀寫鎖
      • for select 與 for range
      • UnBuffered channel 與 Buffered channel
    • Function
    • pointer
    • regExp
    • fmt
    • Make vs New
    • struct
    • Array, Slice 陣列
    • map
  • 核心模組
    • Reflect
    • File
    • Signal
    • BuiltIn
    • Sync
    • IO
    • Sort
    • http
    • crypto
    • context
  • 第三方模組
    • Dom Parser
    • gin 框架
    • Websocket
    • Iris框架
      • 讀取 Body 資料
      • 相關範例
    • Fiber 框架
    • 自動重啟 server 工具
    • go-jwt
  • 測試
  • 原始碼解析
  • 常見問題
    • 資料存取不正確
    • Data races
Powered by GitBook
On this page
  • 基本用法
  • 基本 sort
  • slice sort
  • 實作 slice sort 方法

Was this helpful?

  1. 核心模組

Sort

https://golang.org/pkg/sort/

PreviousIONexthttp

Last updated 3 years ago

Was this helpful?

基本用法

sort.Slice
sort.SliceStable // 將相同值的元素保持原順序
sort.Ints
sort.Float64s
sort.Strings

基本 sort

package main

import (
    "fmt"
    "sort"
)

func main() {

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

    ints := []int{7, 2, 4}
    sort.Ints(ints)
    fmt.Println("Ints:   ", ints)

    s := sort.IntsAreSorted(ints)
    fmt.Println("Sorted: ", s)
}

slice sort

sort.Slice(people, func(i, j int) bool {
  return people[i].Age > people[j].Age
})

實作 slice sort 方法

自行實作 slice 的 sort ,實作時必須要實作三個 func (Len, Less, Swap) 缺一不可。

實作後即可使用 sort.Sort 會依照實作時的 Less 方法排序。

type Person struct {
    Name string
    Age  int
}

// ByAge implements sort.Interface based on the Age field.
type ByAge []Person

func (a ByAge) Len() int           { return len(a) }
func (a ByAge) Less(i, j int) bool { return a[i].Age < a[j].Age }
func (a ByAge) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }

func main() {
    family := []Person{
        {"Alice", 23},
        {"Eve", 2},
        {"Bob", 25},
    }
    sort.Sort(ByAge(family))
    fmt.Println(family) // [{Eve 2} {Alice 23} {Bob 25}]
}

The 3 ways to sort in Goyourbasic_org
Logo