go - 如何将 slice 的副本传递给函数?

标签 go slice

我对将 slice 传递给函数有疑问。

如果我没记错的话, slice 在 Go 中是通过引用传递的,所以如果我这样做:

package main

import "fmt"

func main() {
    slice := []int{1, 2, 3, 4, 5}
    fmt.Println(slice)
    testSlice(slice)
    fmt.Println(slice)
}

func testSlice(slice []int) {
    slice[0] = 5
    slice[4] = 1
}

testSlice 函数实际上会更改原始 slice 中的值,因为它是通过引用传递的(默认情况下)。

有一些简单的方法可以直接将 slice 的副本传递给 testSlice 函数吗?

当然我可以做这样的事情来创建 slice 的副本:

package main

import "fmt"

func main() {
    slice := []int{1, 2, 3, 4, 5}
    fmt.Println(slice)
    testSlice(slice)
    fmt.Println(slice)
}

func testSlice(slice []int) {
    var newSlice []int
    for i := 0; i < len(slice); i++ {
        newSlice = append(newSlice, slice[i])
    }
    newSlice[0] = 5
    newSlice[4] = 1
}

但它需要遍历原始 slice 中的所有值才能复制每个值,这似乎不是一个很好的解决方案。

最佳答案

有一个内置函数,copyfunc copy(dst, src []T) int 这可能就是您要找的。它将任何类型的 slice 复制到另一个 slice 中。

来自docs :

The copy function supports copying between slices of different lengths (it will copy only up to the smaller number of elements). In addition, copy can handle source and destination slices that share the same underlying array, handling overlapping slices correctly.

所以

list := []string{"hello", "world"}
newList := make([]string, len(list))
n := copy(newList, list)
// n is the number of values copied

会将 list 复制到一个新的 slice newList 中,它们共享值但不共享内存中的引用。 int copy 返回的是复制的值的数量。


对于另一种方法,根据 Kostix 的评论,您可以将 slice 附加到空 slice 。这有点像复制它。它可能不是惯用的,但它允许您将 slice 作为副本传递到 func 中,有点。如果您这样做,我建议您发表大量评论。

thisFuncTakesSliceCopy( append([]string(nil), list...) )

要将一个 slice 附加到另一个 slice ,请记住省略号 (...)。

关于go - 如何将 slice 的副本传递给函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43546742/

相关文章:

file - 我应该在同时写入/读取时关闭文件吗?

javascript chop 字符串而不包括标点符号或空格

python - 如何在 Pandas 中选择(切片)多行和多个非连续列?

Python 3 : Getting TypeError: Slices must be integers. .. 但我相信它们

python - 如何在条件满足之前用 N 行中的某些行对条件行进行子集化,比我的代码更快?

arrays - slice - 容量/长度?

go - 如何在 Go 中声明时间?

http - Go 中的简单 HTTP POST 文件上传

multithreading - 如何等待一组 goroutines 中的*任何*发出信号而不需要我们等待它们这样做

regex - 如何解决关于 'filter'字段必须是BSON类型对象的问题