douduan1953 2015-08-24 18:44
浏览 25
已采纳

如何对元素类型为字符串别名而不是字符串本身的Go切片进行排序?

type MyObject string
var objects []MyObject

I want to sort these objects. The standard library has sort.Strings, but that requires an instance of []string instead of []MyObject.

My current solution is to implement sort.Interface (as shown below) and use sort.Sort, but I'd like to get rid of that boilerplate code. Is there a nicer way?

type MyObjects []MyObject

func (objs MyObjects) Len() int {
    return len(objs)
}

func (objs MyObjects) Less(i, j int) bool {
    return strings.Compare(string(objs[i]), string(objs[j])) < 0
}

func (objs MyObjects) Swap(i, j int) {
    o := objs[i]
    objs[i] = objs[j]
    objs[j] = o
}
  • 写回答

2条回答 默认 最新

  • douya2006 2015-08-24 18:56
    关注

    No. Since Go doesn't allow the implicit conversion of types within slices (there is also no covariance with interfaces), you need to supply the appropriate methods for your type.

    type MyObjects []MyObject
    
    func (p MyObjects) Len() int           { return len(p) }
    func (p MyObjects) Swap(i, j int)      { p[i], p[j] = p[j], p[i] }
    func (p MyObjects) Less(i, j int) bool { return p[i] < p[j] }
    

    If you really want to do this, you could use unsafe (but please don't). I doubt those 3 extra lines of safe code are going to make that big a difference for you.

    http://play.golang.org/p/d6ciFjjr2c

    objects := []MyObject{"one", "two", "three", "four"}
    sort.Strings(*(*[]string)(unsafe.Pointer(&objects)))
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100