File tree Expand file tree Collapse file tree 3 files changed +39
-0
lines changed Expand file tree Collapse file tree 3 files changed +39
-0
lines changed Original file line number Diff line number Diff line change @@ -61,3 +61,4 @@ go run . -module closingchannels
61
61
* [ 39 - Atomic Counters] ( atomiccounters/main.go )
62
62
* [ 40 - Mutexes] ( mutexes/main.go )
63
63
* [ 41 - Stateful Goroutines] ( statefulgoroutines/main.go )
64
+ * [ 42 - Sorting] ( sorting/main.go )
Original file line number Diff line number Diff line change @@ -44,6 +44,7 @@ import (
44
44
"github.com/symonk/learning-golang/workerpools"
45
45
"github.com/symonk/learning-golang/mutexes"
46
46
"github.com/symonk/learning-golang/statefulgoroutines"
47
+ "github.com/symonk/learning-golang/sorting"
47
48
)
48
49
49
50
func main () {
@@ -112,5 +113,6 @@ func buildMap() map[string]func() {
112
113
fnMap ["atomiccounters" ] = atomiccounters .Run
113
114
fnMap ["mutexes" ] = mutexes .Run
114
115
fnMap ["statefulgoroutines" ] = statefulgoroutines .Run
116
+ fnMap ["sorting" ] = sorting .Run
115
117
return fnMap
116
118
}
Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments