Example39 go from the beginning of the language examples using a custom sort function

Sometimes we want to use a collection of different natural and sorting methods to sort the collection. For example, we want to follow the letter rather than the length of the first alphabetically sort strings. Here is an example of a custom sort of Go.

Example:

package main
import (
    "fmt"
    "sort"
)

// To use a custom function in Go sort
 // type we need a corresponding.
// Here we create one of the built-in [] byLength type alias string type,
type byLength []string

// we achieve in the sort.Interface type of Len, Less, and Swap method,
 // so that we can use the Sort method common package of the sort, Len and Swap 
 // usually are similar in various types, Less control the actual ordering custom logic.
// In our example, we want to increase the length of the string according to the sorted order, so here using len (s [i]) and len (s [j]).
func (s byLength) Len() int{
    return len(s)
}

func (s byLength) Swap(i, j int){
    s[i], s[j] = s[j], s[i]
}

func (s byLength) Less(i, j int) bool{
    return len (p [i]) < only (p [j])
}


func main() {
    // everything is ready, we can now achieve our custom ordering by the original sortstr slice transition into byLength.
    // then use sort.Sort approach to this transition slices.
    sortstr := []string{"abc", "abcd", "ab"}
    sort.Sort(byLength(sortstr))
    fmt.Println(sortstr)
}

Result:

$ go run example.go
[ab abc abcd]

 

Coordinates: previous example    next example

 

Guess you like

Origin www.cnblogs.com/yhleng/p/11775087.html