Golang : Sort and reverse sort a slice of runes
Problem :
How to sort and reverse sort a slice of runes ?
Solution :
Sorting runes depends on the integer value of the rune and it will be ordered according to the integer values . Here's an example of how to sort slice of runes :
package main
import (
"fmt"
"sort"
)
type RuneSlice []rune
func (p RuneSlice) Len() int { return len(p) }
func (p RuneSlice) Less(i, j int) bool { return p[i] < p[j] }
func (p RuneSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
var runes RuneSlice = []rune{'可', '愛'} // sort based on the integer values of the runes
func main() {
// Runes
fmt.Println("Original : ", runes[:])
fmt.Println("Original : ", string(runes[:]))
sort.Sort(RuneSlice(runes))
fmt.Println("Sort : ", runes[:])
fmt.Println("Sort : ", string(runes[:]))
sort.Sort(sort.Reverse(runes[:]))
fmt.Println("Reverse : ", runes[:])
fmt.Println("Reverse : ", string(runes[:]))
}
Output :
Original : [21487 24859]
Original : 可愛
Sort : [21487 24859]
Sort : 可愛
Reverse : [24859 21487]
Reverse : 愛可
UPDATE : You can import "github.com/cznic/sortutil" and use the RuneSlice.Sort() method ( see http://godoc.org/github.com/cznic/sortutil#RuneSlice ) as well if you prefer.
See also : Golang : Sort and reverse sort a slice of bytes
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+4.6k Golang : Launching your executable inside a console under Linux
+19.7k SSL : How to check if current certificate is sha1 or sha2
+20.5k Golang : untar or extract tar ball archive example
+9.2k Golang : Simple image viewer with Go-GTK
+3.5k Nginx and PageSpeed build from source CentOS example
+10.2k Golang : Setup API server or gateway with Caddy and http.ListenAndServe() function example
+5.6k Golang : Takes a plural word and makes it singular
+3.8k Linux/Unix/MacOSX : Find out which application is listening to port 80 or use which IP version
+5.8k Ubuntu : connect() to unix:/var/run/php5-fpm.sock failed (13: Permission denied) while connecting to upstream
+3.6k Linux/MacOSX : How to symlink a file?
+4.7k Golang : Compound interest over time example
+5.6k Golang : Trim everything onward after a word