英文:
Go - How to copy slice of an interface?
问题
我正在尝试使用辅助数组实现一个简单的归并排序。我有一个type byString []string
,它实现了Less、Swap和Len
方法。它基本上遵循了Go的sort
包的接口。
然而,我在选择将byString
切片复制到临时数组时遇到了一些困难。
请帮助我摆脱Java的多态世界,使其在Go中正常工作。
func merge(data Interface, lo, mid, hi int) {
i, j := lo, mid+1
// 我该如何将data的元素复制到名为aux的新切片中?
}
英文:
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. It's basically following Go's sort
package's interface.
However, I'm having some difficulty choosing the best route to copy the byString
slice to a temporary array.
Please help me break out of Java's polymorphism world to make it work with 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?
}
答案1
得分: 1
使用内置的copy
函数,你只需要将新的切片声明为接口类型:
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)
}
英文:
Use the built-in copy
function, you just have to declare the new slice as an interface type:
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)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论