LoginSignup
8
8

More than 5 years have passed since last update.

Golang:複数条件でソートする

Last updated at Posted at 2018-03-16

華麗なコードではない。

バージョン

golang

1.8.7くらい

実装

package main

import (
    "fmt"
    "sort"
)

func main() {
    people := []struct {
        Name string
        Age  int
    }{
        {"Steve", 70},
        {"Carol", 99},
        {"Alice", 100},
        {"Bob", 1},        
        {"Alice", 26},
    }

    sort.Slice(people, func(i, j int) bool {
        if people[i].Name < people[j].Name {
            return true
        } else if people[i].Name == people[j].Name {
            if people[i].Age < people[j].Age {
                return true
            }
        }
        return false
    })
    fmt.Println("Order by name, age:", people)
}

出力結果

Order by name, age: [{Alice 26} {Alice 100} {Bob 1} {Carol 99} {Steve 70}]

参考

8
8
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
8
8