сортировка через функции

This commit is contained in:
badkaktus 2019-10-08 22:06:57 +03:00
parent ee38f601f3
commit 7dabb31483
3 changed files with 29 additions and 28 deletions

View File

@ -38,7 +38,7 @@ WaitGroups
Мьютексы (Mutexes) Мьютексы (Mutexes)
Управление состоянием горутин (Stateful Goroutines) Управление состоянием горутин (Stateful Goroutines)
Сортировка (Sorting) Сортировка (Sorting)
Sorting by Functions Сортировка через функции (Sorting by Functions)
Panic Panic
Defer Defer
Collection Functions Collection Functions

View File

@ -1,8 +1,8 @@
// Sometimes we'll want to sort a collection by something // Иногда мы хотим отсортировать коллекцию по какому-то
// other than its natural order. For example, suppose we // другому признаку, кроме ее естественного порядка.
// wanted to sort strings by their length instead of // Например, предположим, что мы хотели бы отсортировать
// alphabetically. Here's an example of custom sorts // строки по длине, а не по алфавиту. Вот пример
// in Go. // пользовательских сортировок в Go.
package main package main
@ -11,19 +11,20 @@ import (
"sort" "sort"
) )
// In order to sort by a custom function in Go, we need a // Для сортировки по пользовательской функции в Go нам
// corresponding type. Here we've created a `byLength` // нужен соответствующий тип. Здесь мы создали тип
// type that is just an alias for the builtin `[]string` // `byLength`, который является просто псевдонимом для
// type. // `[]string`.
type byLength []string type byLength []string
// We implement `sort.Interface` - `Len`, `Less`, and // Мы реализуем `sort.Interface` - Len`, `Less` и `Swap`
// `Swap` - on our type so we can use the `sort` package's // - для нашего типа, чтобы мы могли использовать общую
// generic `Sort` function. `Len` and `Swap` // функцию `Sort` пакета `sort`. `Len` и `Swap` обычно
// will usually be similar across types and `Less` will // одинаковы для разных типов, а `Less` будет содержать
// hold the actual custom sorting logic. In our case we // реальную пользовательскую логику сортировки. В нашем
// want to sort in order of increasing string length, so // случае мы хотим отсортировать в порядке увеличения
// we use `len(s[i])` and `len(s[j])` here. // длины строки, поэтому мы используем `len(s[i])` и
// `len(s[j])` здесь.
func (s byLength) Len() int { func (s byLength) Len() int {
return len(s) return len(s)
} }
@ -34,10 +35,10 @@ func (s byLength) Less(i, j int) bool {
return len(s[i]) < len(s[j]) return len(s[i]) < len(s[j])
} }
// With all of this in place, we can now implement our // Реализовав интерфейс, мы можем теперь реализовать
// custom sort by converting the original `fruits` slice // нашу собственную сортировку, преобразовав исходный
// to `byLength`, and then use `sort.Sort` on that typed // срез `fruits` в `byLength`, а затем использовать
// slice. // `sort.Sort` для этого типизированного среза.
func main() { func main() {
fruits := []string{"peach", "banana", "kiwi"} fruits := []string{"peach", "banana", "kiwi"}
sort.Sort(byLength(fruits)) sort.Sort(byLength(fruits))

View File

@ -1,10 +1,10 @@
# Running our program shows a list sorted by string # При запуске нашей программы отображается список,
# length, as desired. # отсортированный по длине строки, как мы и хотели.
$ go run sorting-by-functions.go $ go run sorting-by-functions.go
[kiwi peach banana] [kiwi peach banana]
# By following this same pattern of creating a custom # Следуя той же схеме создания пользовательского типа,
# type, implementing the three `Interface` methods on that # реализации трех методов `интерфейса` для этого типа
# type, and then calling sort.Sort on a collection of that # и последующего вызова `sort.Sort` для коллекции
# custom type, we can sort Go slices by arbitrary # этого типа, мы можем сортировать срезы Go
# functions. # по произвольным функциям.