为什么在 Go 中,当传递一个切片时,append 函数使用引用工作?

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

Why the function append in Go work with reference when pass a slice?

问题

在下面的代码中,我试图向一个切片的切片中添加一个元素,但是由于Go语言使用引用,我该如何通过使用切片b的值来实现呢?

package main

import (
    "fmt"
)

func main() {
    a := []int{1}
    arr := [][]int{a}

    b := []int{2}

    arr = append(arr, b)
    fmt.Println(arr)

    b[0] = 3
    arr = append(arr, b)

    fmt.Println(arr)
}

我期望最后的Println输出是[[1] [2] [3]],但实际输出是[[1] [3] [3]]。

英文:

In the next code I'm trying to add an element of a slice of slices, but as Go works with reference, how can I use this by using the b slice by value?

package main

import (
    "fmt"
)

func main() {
    a := []int{1}
    arr := [][]int{a}

    b := []int{2}

    arr = append(arr, b)
    fmt.Println(arr)

    b[0] = 3
    arr = append(arr, b)   

    fmt.Println(arr)
}

I expected that the last Println was [[1] [2] [3]], but it's [[1] [3] [3]].

答案1

得分: 3

没有办法通过值来插入一个切片;在插入之前,你需要对切片进行复制

package main

import (
    "fmt"
)

func copy_ints(c []int) []int {
    s := make([]int, len(c))
    copy(s, c)
    return s
}

func main() {
    a := []int{1}
    arr := [][]int{copy_ints(a)}

    b := []int{2}

    arr = append(arr, copy_ints(b))
    fmt.Println(arr)

    b[0] = 3
    arr = append(arr, copy_ints(b))

    fmt.Println(arr)
}

你可以在这里运行这段代码。

英文:

There is no way to insert a slice "by value"; you need to make a copy of the slice before inserting it:

package main

import (
    "fmt"
)

func copy_ints(c []int) []int {
    s := make([]int, len(c))
    copy(s, c)
    return s
}

func main() {
    a := []int{1}
    arr := [][]int{copy_ints(a)}

    b := []int{2}

    arr = append(arr, copy_ints(b))
    fmt.Println(arr)

    b[0] = 3
    arr = append(arr, copy_ints(b))

    fmt.Println(arr)
}

https://play.golang.org/p/Tds5FGj3nf

huangapple
  • 本文由 发表于 2016年4月6日 23:15:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/36455328.html
匿名

发表评论

匿名网友

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

确定