繁星點(diǎn)點(diǎn)滴滴
2022-05-23 14:52:11
我想看看是否有一種簡單的方法可以用另一個(gè)切片的所有值替換切片的一部分。例如:x := []int{1,2,0,0}y := []int{3,4}// goal is x == {1,2,3,4}x[2:] = y // compile errorx[2:] = y[:] // compile error我知道我總是可以遍歷 y,但是 Go 有很多很酷的特性,而且我對 Go 還是很陌生。所以也許我會以錯(cuò)誤的方式解決這個(gè)問題。
1 回答

守著星空守著你
TA貢獻(xiàn)1799條經(jīng)驗(yàn) 獲得超8個(gè)贊
您可以使用內(nèi)置副本:
復(fù)制內(nèi)置函數(shù)將元素從源切片復(fù)制到目標(biāo)切片。
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
從上面的評論中竊取,您可以在此處了解有關(guān)切片的更多信息:
https://golang.org/ref/spec#Appending_and_copying_slices
https://golang.org/doc/effective_go.html#slices
https://github.com/golang/go/wiki/SliceTricks
我還發(fā)現(xiàn)這篇博文內(nèi)容豐富:https ://divan.dev/posts/avoid_gotchas/#arrays-and-slices
- 1 回答
- 0 關(guān)注
- 172 瀏覽
添加回答
舉報(bào)
0/150
提交
取消