[英]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.