drnbotxo449747 2015-08-02 21:05
浏览 23
已采纳

转换类型以进行排序:运行时需要任何费用吗?

I'm just getting to grips with Go (started two days ago and wrote less than 1000 lines), and I'm still wondering about some idioms.

I needed to sort a slice of strings by descending length. I did like so :

func ... {
    ... do business ...

    sort.Sort(stringsLongestFirst(severalThousandStrings))

    ... carry on and be happy, because it works ...
}

type stringsLongestFirst []string

func (b stringsLongestFirst) Len() int           { return len(b) }
func (b stringsLongestFirst) Less(i, j int) bool { return len(b[i]) > len(b[j]) }
func (b stringsLongestFirst) Swap(i, j int)      { b[j], b[i] = b[i], b[j] }

First of all I wonder if this is the most idiomatic way to do it.

And then, most of all, I wonder about what happens under the hood when I write stringsLongestFirst(severalThousandStrings). Does the string slice somehow get smartly reinterpreted as a stringsLongestFirst type, or do I have to count with some copying overhead ?

(edited : removed the excerpt from the specification, that was ill-suited to the case at hand)

  • 写回答

1条回答 默认 最新

  • duandou9931 2015-08-03 01:38
    关注

    The types you are converting is neither a numeric type or a string: []string and stringsLongestFirst are slice types.

    So the conversion should incur no more overhead than copying the slice header (which is 12 or 24 bytes, depending on the word size), which would happen anyway when packing it as an interface{} variable in order to call Sort. The backing array is not copied, which is why severalThousandStrings appears to be sorted after the call.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?