The example in this article describes the go language sorting and interface usage. Share to everyone for your reference. Specifically as follows:
Copy Code code as follows:
Import "FMT"
Type Sorter Interface {
Len () int
Less (i, J int) bool
Swap (i, J int)
}
Type Xi []int
Type Xs []string
Func (P Xi) len () int {return Len (p)}
Func (P Xi) less (i int, j int) bool {return P[J] < P[i]}
Func (P Xi) Swap (i int, j int) {P[i], p[j] = P[j], P[i]}
Func (P Xs) Len () int {return Len (p)}
Func (P Xs) less (i int, j int) bool {return P[J] < P[i]}
Func (P Xs) Swap (i int, j int) {P[i], p[j] = P[j], P[i]}
Func Sort (x Sorter) {
For I: = 0; I < X.len ()-1; i++ {
For J: = i + 1; J < X.len (); J + + {
If X.less (i, j) {
X.swap (i, J)
}
}
}
}
Func Main () {
INTs: = xi{44, 67, 3, 17, 89, 10, 73, 9, 14, 8}
Strings: = xs{"nut", "ape", "Elephant", "Zoo", "Go"}
Sort (INTs)
Fmt. Printf ("%v\n", INTs)
Sort (Strings)
Fmt. Printf ("%v\n", strings)
}
I hope this article will help you with your go language program.