Go – How to copy slice of an interface?

huangapple go评论97阅读模式
英文:

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)
}

huangapple
  • 本文由 发表于 2016年5月28日 09:06:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/37494264.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定