如何在go中将切片的一部分替换为另一部分



我想看看是否有一种简单的方法可以用另一个切片的所有值替换切片的一部分。例如:

x := []int{1,2,0,0}
y := []int{3,4}
// goal is x == {1,2,3,4}
x[2:] = y    // compile error
x[2:] = y[:] // compile error

我知道我总是可以通过y迭代,但Go有很多很酷的功能,我对Go还很陌生。所以也许我做这件事的方式不对。

您可以使用内置副本:

复制内置函数将元素从源切片复制到目标切片。

package main
import "fmt"
func main() {
x := []int{1, 2, 0, 0}
y := []int{3, 4}
copy(x[2:], y)
fmt.Println(x) // [1 2 3 4]
}
  • https://play.golang.org/p/TL6Bv4OGeqE

从上面的评论中窃取,你可以在这里了解更多关于切片的信息:

  • https://golang.org/ref/spec#Appending_and_copying_slices
  • https://golang.org/doc/effective_go.html#slices
  • https://github.com/golang/go/wiki/SliceTricks

我还发现这篇博客文章内容丰富:https://divan.dev/posts/avoid_gotchas/#arrays-并对进行切片

x/exp/slices中有一个Replace函数:

Replace用给定的v替换元素s[i:j],并返回修改后的切片。如果s[i:j]不是s的有效切片,则替换恐慌。

import (
"fmt"
"golang.org/x/exp/slices"
)
func main() {
x := []int{1, 2, 0, 0}
y := []int{3, 4}
z := slices.Replace(x, 2, 4, y...)
fmt.Println(z)
}

游乐场

最新更新