简体   繁体   English

Go-如何复制界面切片?

[英]Go - How to copy slice of an interface?

I'm trying to implement a simple merge sort using an auxiliary array. 我正在尝试使用辅助数组实现简单的合并排序。 I have type byString []string that implements the Less, Swap, and Len methods. 我有type byString []string ,它实现了Less, Swap, and Len方法。 It's basically following Go's sort package's interface. 它基本上遵循Go的sort包的界面。

However, I'm having some difficulty choosing the best route to copy the byString slice to a temporary array. 但是,我在选择最佳方法以将byString切片复制到临时数组时遇到一些困难。

Please help me break out of Java's polymorphism world to make it work with Go. 请帮助我突破Java的多态世界,使其与Go一起使用。

func merge(data Interface, lo, mid, hi int) {
  i, j := lo, mid+1

  // How do I copy data's elements to a new slice called aux?
}

Use the built-in copy function, you just have to declare the new slice as an interface type: 使用内置的copy功能,您只需要将新的slice声明为接口类型:

type Interface []string

func merge(data Interface, lo, mid, hi int) {
    i, j := lo, mid+1
    var aux Interface = make([]string, len(data), len(data))
    copy(aux, data)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM