Golang中的数组赋值:内容副本或内容指针副本

时间:2018-03-10 04:58:12

标签: arrays go

在Golang中学习数组数据结构的细微差别时,我遇到了一个有趣的混乱。我从blog.golang.org了解到 -

  

当您指定或传递数组值时,您将   制作其内容的副本。

为了自己查看,我写了以下代码:

package main

import "fmt"

func main() {
    x := []int{2, 4, 5}
    y := x

    y[0] = -10

    // expecting 2 here but getting -10, since  y := x is supposed to be a content copy
    fmt.Println(x[0])

    // not same
    println("&x: ", &x)
    println("&y: ", &y)

    // same
    println("&x[0]: ", &x[0])
    println("&y[0]: ", &y[0])
}

做同样的事情是java我得到了与x和y相同的内部对象地址。

转码:https://play.golang.org/p/04l0l84eT4J

Java代码:https://pastebin.ubuntu.com/p/S3fHMTj5NC/

1 个答案:

答案 0 :(得分:2)

您的 patchValues() { let rows = this.myForm.get('rows') as FormArray; this.orders.forEach(material => { material.materials.forEach(x => { rows.push(this.fb.group({ checkbox_value: [null], material_id: new FormControl({value: x.id, disabled: true}, Validators.required), material_name: x.name, quantity: [null, Validators.required] })) }) }) }

x

slice,而不是array

如果你使x := []int{2, 4, 5} 成为一个数组:

x

然后您会看到您期待的结果:

x := [3]int{2, 4, 5}
// ---^ Now it is an array

产生如下输出:

package main

import "fmt"

func main() {
    x := [3]int{2, 4, 5}
    y := x

    y[0] = -10

    // expecting 2 here, since it is supposed to be a content copy
    fmt.Println(x[0])

    // not same
    fmt.Println("&x: ", &x)
    fmt.Println("&y: ", &y)

    // same (not anymore...)
    fmt.Println("&x[0]: ", &x[0])
    fmt.Println("&y[0]: ", &y[0])
}

https://play.golang.org/p/-3ZNPwlD1WT