and*_*ras 17 sorting string go slice rune
我无法按字符排序字符串(检查两个字符串是否为字谜,我想对它们进行排序,并检查是否相等).
我可以得到这样[]rune
的字符串表示s
:
runes := make([]rune, len(s))
copy(runes, []rune(s))
Run Code Online (Sandbox Code Playgroud)
我可以像这样排序
someInts := []int{5, 2, 6, 3, 1, 4} // unsorted
sort.Ints(someInts)
Run Code Online (Sandbox Code Playgroud)
但这rune
只是一个别名,int32
所以我应该可以打电话
sort.Ints(runes)
Run Code Online (Sandbox Code Playgroud)
但是,我收到错误:
cannot use runes (type []rune) as type []int in function argument
Run Code Online (Sandbox Code Playgroud)
那么......我如何对int32,int64或int*进行排序?
编辑:我确实得到了我的符文排序,但男孩,这是丑陋的.
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] }
func sorted(s string) string {
runes := []rune(s)
sort.Sort(RuneSlice(runes))
return string(runes)
}
Run Code Online (Sandbox Code Playgroud)
所以基本上如果你有一些东西,你必须将它包装在一个实现的类型中 sort.Interface
.所有这些实现都将具有完全相同的方法体(如sort.IntSlice
和sort.Float64Slice
).如果这真的是多么丑陋,那么为什么他们不在包装中提供这些WhateverSlice包装sort
?缺乏仿制药现在开始受到非常严重的伤害.必须有一种更好的分类方法.
使用sort.Sort(data Interface)
和实现sort.Interface
,请参阅包文档中的示例.
您不能使用rune
它int32
作为int
.检查意见的int
.
int是有符号整数类型,其大小至少为32位.但是,它是一种不同的类型,而不是int32的别名.
注意:Go 1.8 将引入用于对切片进行排序的助手。
请参阅问题 16721并提交Brad Fitzpatrick的22a2bdf
var strings = [...]string{"", "Hello", "foo", "bar", "foo", "f00", "%*&^*&^&", "***"}
func TestSlice(t *testing.T) {
data := strings
Slice(data[:], func(i, j int) bool {
return data[i] < data[j]
})
}
Run Code Online (Sandbox Code Playgroud)