Skip to content

Commit 9e9df29

Browse files
committed
42: Sorting
1 parent ce59e92 commit 9e9df29

File tree

3 files changed

+39
-0
lines changed

3 files changed

+39
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,3 +61,4 @@ go run . -module closingchannels
6161
* [39 - Atomic Counters](atomiccounters/main.go)
6262
* [40 - Mutexes](mutexes/main.go)
6363
* [41 - Stateful Goroutines](statefulgoroutines/main.go)
64+
* [42 - Sorting](sorting/main.go)

main.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@ import (
4444
"github.com/symonk/learning-golang/workerpools"
4545
"github.com/symonk/learning-golang/mutexes"
4646
"github.com/symonk/learning-golang/statefulgoroutines"
47+
"github.com/symonk/learning-golang/sorting"
4748
)
4849

4950
func main() {
@@ -112,5 +113,6 @@ func buildMap() map[string]func() {
112113
fnMap["atomiccounters"] = atomiccounters.Run
113114
fnMap["mutexes"] = mutexes.Run
114115
fnMap["statefulgoroutines"] = statefulgoroutines.Run
116+
fnMap["sorting"] = sorting.Run
115117
return fnMap
116118
}

sorting/main.go

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
package sorting
2+
3+
import (
4+
"fmt"
5+
"slices"
6+
"sort"
7+
)
8+
9+
// Go `slices` package implements sorting for
10+
// builtin types and user defined types.
11+
func Run() {
12+
sortingBuiltIn()
13+
sortingCustomType()
14+
}
15+
16+
// Sorting a builtin type
17+
func sortingBuiltIn() {
18+
strings := []string{"foo", "bar", "baz"}
19+
slices.Sort(strings)
20+
fmt.Println(strings)
21+
// ["bar", "baz", "foo"]
22+
}
23+
24+
// A custom struct, sortable by an attribute.
25+
type Foo struct {
26+
x int
27+
}
28+
29+
// Sorting a user defined; custom type
30+
func sortingCustomType() {
31+
foos := []Foo{Foo{x: 3}, Foo{x: 2}, Foo{x: 100}, Foo{x: 1}}
32+
sort.Slice(foos[:], func(i, j int) bool {
33+
return foos[i].x < foos[j].x
34+
})
35+
fmt.Println(foos)
36+
}

0 commit comments

Comments
 (0)