## 2020年6月7日日曜日

### Go - Go Packages, Algorithms, and Data Structures - sortパッケージ、Slice関数、引数、less関数、無名関数、関数リテラル

Go Systems Programming: Master Linux and Unix system level programming with Go (Mihalis Tsoukalos(著)、Packt Publishing)のChapter 4(Go Packages, Algorithms, and Data Structures)、Exercises 2.の解答を求めてみる。

コード

```package main

import (
"fmt"
"sort"
"strings"
)

type person struct {
name string
age  int
}

func p(p1, p2 []person) {
fmt.Println(p1)
fmt.Println(p2)
fmt.Println()
}
func main() {
people := []person{
person{name: "a", age: 5},
person{name: "b", age: 1},
person{name: "日本語", age: 4},
person{name: "c", age: 2},
person{name: "aaa", age: 3},
person{name: "a", age: 1},
}
people1 := make([]person, len(people))
copy(people1, people)
p(people, people1)

sort.Slice(people, func(i, j int) bool {
return strings.Compare(people[i].name, people[j].name) == -1
})
p(people, people1)

sort.Slice(people, func(i, j int) bool {
return people[i].age < people[j].age
})
p(people, people1)

sort.Slice(people1, func(i, j int) bool {
return people1[i].age < people1[j].age
})
p(people, people1)

sort.Slice(people1, func(i, j int) bool {
return strings.Compare(people1[i].name, people1[j].name) == -1
})
p(people, people1)

people = append(people, person{name: "a", age: 0})
sort.Slice(people, func(i, j int) bool {
switch strings.Compare(people[i].name, people[j].name) {
case -1:
return true
case 1:
return false
default:
return people[i].age < people[j].age
}
})
fmt.Println(people)
}
```

```% go run sample2.go
[{a 5} {b 1} {日本語 4} {c 2} {aaa 3} {a 1}]
[{a 5} {b 1} {日本語 4} {c 2} {aaa 3} {a 1}]

[{a 5} {a 1} {aaa 3} {b 1} {c 2} {日本語 4}]
[{a 5} {b 1} {日本語 4} {c 2} {aaa 3} {a 1}]

[{a 1} {b 1} {c 2} {aaa 3} {日本語 4} {a 5}]
[{a 5} {b 1} {日本語 4} {c 2} {aaa 3} {a 1}]

[{a 1} {b 1} {c 2} {aaa 3} {日本語 4} {a 5}]
[{b 1} {a 1} {c 2} {aaa 3} {日本語 4} {a 5}]

[{a 1} {b 1} {c 2} {aaa 3} {日本語 4} {a 5}]
[{a 1} {a 5} {aaa 3} {b 1} {c 2} {日本語 4}]

[{a 0} {a 1} {a 5} {aaa 3} {b 1} {c 2} {日本語 4}]
%
```