LoginSignup
4
1

More than 3 years have passed since last update.

複数条件でのsort.Sliceの書き方工夫

Posted at

Goで↓みたいな並び替えをしたい場合。

xxxで 降順、同じならyyyで降順、それも同じならzzzで降順。

素朴に書くとless関数がこんな感じになるんだけど…

if a.xxx < b.xxx {
  return true
}

if a.xxx > b.xxx {
  return false
}

if a.yyy < b.yyy {
  return true
}

if a.yyy > b.yyy {
  return false
}

return a.zzz < b.zzz

switch文で組み立てると{}がなくなるので少しマシになるみたい。

package main

import (
    "fmt"
    "sort"
)

type person struct {
    firstName string
    lastName  string
    age       int
}

func main() {
    people := []person{
        {"taro", "tanaka", 20},
        {"hanako", "suzuki", 21},
        {"taro", "sato", 22},
        {"taro", "sato", 21},
    }
    fmt.Println(people)
    sort.Slice(people, func(i, j int) bool {
        a, b := people[i], people[j]
        switch {
        case a.firstName < b.firstName:
            return true
        case a.firstName > b.firstName:
            return false
        case a.lastName < b.lastName:
            return true
        case a.lastName > b.lastName:
            return false
        default:
            return a.age < b.age
        }
    })
    fmt.Println(people)
}

しかし、もう少し短くできないだろうか。。

4
1
1

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
4
1