refactor: iface sorting

This commit is contained in:
Inanc Gumus
2019-10-23 21:00:05 +03:00
parent 3ac59459fd
commit f0200eface
6 changed files with 18 additions and 18 deletions

View File

@ -65,5 +65,5 @@ func (bp byRelease) Swap(i, j int) { bp.list.Swap(i, j) }
*/
func byReleaseDate(l list) sort.Interface {
return &byRelease{l}
return byRelease{l}
}

View File

@ -9,6 +9,7 @@ package main
import (
"fmt"
"sort"
)
func main() {
@ -18,10 +19,10 @@ func main() {
{title: "hobbit", price: 25},
}
// sort.Sort(l)
// sort.Sort(sort.Reverse(l))
// sort.Sort(byReleaseDate(l))
// sort.Sort(sort.Reverse(byReleaseDate(l)))
sort.Sort(l)
sort.Sort(sort.Reverse(l))
sort.Sort(byReleaseDate(l))
sort.Sort(sort.Reverse(byReleaseDate(l)))
fmt.Print(l)
}
@ -33,13 +34,14 @@ Summary:
- sort.Interface has three methods: Len(), Less(), Swap()
- Len() returns the length of a collection.
- Less() should return true when an element comes before another one.
- Swap()s the elements when Less() returns true.
- Less(i, j) should return true when an element comes before another one.
- Swap(i, j)s the elements when Less() returns true.
- sort.Reverse() sorts a sort.Interface value.
- sort.Reverse() can reverse sort a type that satisfies the sort.Interface.
- You can customize the sorting:
- by anonymously embedding the sort.Interface type
- Either by implementing the sort.Interface methods,
- or by anonymously embedding a type that already satisfies the sort.Interface
- and adding a Less() method.
- Anonymous embedding means auto-forwarding method calls to an embedded value.

View File

@ -50,5 +50,5 @@ func (bp byRelease) Less(i, j int) bool {
}
func byReleaseDate(l list) sort.Interface {
return &byRelease{l}
return byRelease{l}
}

View File

@ -34,14 +34,12 @@ func main() {
Summary:
- json.Marshal() and json.MarshalIndent() can only encode primitive types.
- It cannot encode custom types.
- Implement the json.Marshaler interface and teach it how to encode your custom types.
- See time.Time code: It satisfies the json.Marshaler interface.
- Custom types can tell the encoder how to encode.
- To do that satisfy the json.Marshaler interface.
- json.Unmarshal() can only decode primitive types.
- It cannot decode custom types.
- Implement the json.Unmarshaler interface and teach it how to decode your custom types.
- See time.Time code: It satisfies the json.Unmarshaler interface as well.
- Custom types can tell the decoder how to decode.
- To do that satisfy the json.Unmarshaler interface.
- strconv.AppendInt() can append an int value to a []byte.
- There are several other functions in the strconv package for other primitive types as well.

View File

@ -50,5 +50,5 @@ func (bp byRelease) Less(i, j int) bool {
}
func byReleaseDate(l list) sort.Interface {
return &byRelease{l}
return byRelease{l}
}

View File

@ -50,5 +50,5 @@ func (bp byRelease) Less(i, j int) bool {
}
func byReleaseDate(l list) sort.Interface {
return &byRelease{l}
return byRelease{l}
}