Upgrade to Pro — share decks privately, control downloads, hide ads and more …

昔のGo, 今のGo ~比較, ソート編~

昔のGo, 今のGo ~比較, ソート編~

kamakura.go #6, 2024-05-17

Shoichi Kaji

May 17, 2024
Tweet

More Decks by Shoichi Kaji

Other Decks in Programming

Transcript

  1. time.Compare • time.Timeʹ͸࣌ࠁ͕"લ"͔൱͔Λฦ͢Beforeϝιου͕͋Δ: func (t Time) Before(t2 Time) bool •

    go1.20ͰCompareϝιου͕௥Ճ͞Εͨ: func (t Time) Compare(t2 Time) int • t͕t2ΑΓ"લ"ͳΒ: -1 t͕t2ͱ"౳͍͠"ͳΒ: 0 t͕t2ΑΓ"ޙΖ"ͳΒ: +1
  2. slices.Sort/SortFunc • sort packageʹSlice,Sortؔ਺͕ఆٛ͞Ε͍ͯΔ: func Slice(x any, less func(i, j

    int) bool) func Sort(x Interface) • εϥΠεͷιʔτ͸্هͷͲͪΒ͔Λ࢖͏ͷ͕Ұൠతͩͬͨ • Slice: εϥΠεΛanyͰड͚औ͍ͬͯΔ 🥲 • Sort: sort.InterfaceΛຬͨ͢ɺLen, Less, Swapϝιου Λ࣮૷ͨ͠ܕΛΘ͟Θ͟࡞Βͳ͍ͱ͍͚ͳ͍ 🥲
  3. slices.Sort/SortFunc • go1.21Ͱೖͬͨslices packageʹgenericsΛ࢖ͬͨε ϥΠεͷιʔτؔ਺͕ఆٛ͞Ε͍ͯΔ func Sort[S ~[]E, E cmp.Ordered](x

    S) func SortFunc[S ~[]E, E any](x S, compare func(a, b E) int) • ܕ͕͍ͭͨঢ়ଶͰεϥΠεΛड͚औΔ 😊 • ιʔτ৚݅Λࣔ͢Ҿ਺ͷؔ਺͕ɺless͔ΒcompareʹมΘ͍ͬͯΔ ͜ͱʹ΋஫໨͍ͨ͠ • ࠓޙ͸sort.Sort/SliceͰ͸ͳͪ͘͜ΒΛ࢖͏ͱΑͦ͞͏
  4. ෳ਺ͷιʔτ৚݅ • ෳ਺ͷιʔτ৚݅compare1,2,3Λ૊Έ߹Θͤෳࡶ ͳιʔτ৚݅Λॻ͘͜ͱ͕͋Δ: • compare := func(e1, e2 E)

    int { if c := compare1(e1, e2); c != 0 { return c } if c := compare2(e1, e2); c != 0 { return c } return compare3(e1, e2) }