Golang数组指针

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

Golang Array Pointer

问题

我想解释一下在Golang中的这种行为,为什么当你在数组上获取内存引用并且通过这个引用改变值时,引用的数组中的值不会改变。

一个例子:

var t [5]int
printType(t,"t")
p := &t
printType(p,"p")
x := *p
x[0] = 4
printType(x,"x")
printType(p,"p")
printType(t,"t")

这段代码返回:

[t] Type:[5]int Kind:array Adr:%!p([5]int=[0 0 0 0 0]) Value:([0 0 0 0 0])

Type:*[5]int Kind:ptr Adr:0xc4200142d0 Value:(&[0 0 0 0 0]) [x] Type:[5]int Kind:array Adr:%!p([5]int=[4 0 0 0 0]) Value:([4 0 0 0 0])

Type:*[5]int Kind:ptr Adr:0xc4200142d0 Value:(&[0 0 0 0 0]) [t] Type:[5]int Kind:array Adr:%!p([5]int=[0 0 0 0 0]) Value:([0 0 0 0 0])

你可以看到内存地址是相同的,但值"4"并不存在。

printType方法:

func printType(i interface{}, message string) {
    k := reflect.TypeOf(i).Kind().String()
    fmt.Printf("[%s] Type:%T Kind:%s Adr:%[2]p Value:(%[2]v)\n", message, i, k)
}
英文:

I want to elucidate this behavior in Golang,
Why when you take the memory reference on array and you change values from this reference nothing change in the referencing array.

One example :

var t [5]int
printType(t,"t")
p := &t
printType(p,"p")
x := *p
x[0] = 4
printType(x,"x")
printType(p,"p")
printType(t,"t")

This code return

[t] Type:[5]int Kind:array Adr:%!p([5]int=[0 0 0 0 0]) Value:([0 0 0 0 0])

Type:*[5]int Kind:ptr Adr:0xc4200142d0 Value:(&[0 0 0 0 0]) [x] Type:[5]int Kind:array Adr:%!p([5]int=[4 0 0 0 0]) Value:([4 0 0 0 0])

Type:*[5]int Kind:ptr Adr:0xc4200142d0 Value:(&[0 0 0 0 0]) [t] Type:[5]int Kind:array Adr:%!p([5]int=[0 0 0 0 0]) Value:([0 0 0 0 0])

you can see the memory address is the same but the value "4" is not present.

Method printType

func printType(i interface {},message string) {
   k := reflect.TypeOf(i).Kind().String()
   fmt.Printf("[%s] Type:%T Kind:%s Adr:%[2]p Value:(%[2]v)\n",message,i,k)
}

答案1

得分: 2

好的,以下是翻译好的内容:

> 好的,找到了,运算符":="分配一个新的内存地址。

不,它不会分配任何东西。

var t [5]int 是一个值。请注意,根据规范,在这种情况下[5]int是完整的类型名称。你可以将其视为具有5个int字段的结构体。x := *p这一行对指向t(一个值)的指针进行解引用。赋值操作会创建一个副本。如果你想要传递一个对t的"引用",可以使用切片:t[:]

英文:

> Okay found it, the operator ":=" allocate an new memory address.

No, it doesn't allocate anything.

var t [5]int is a value. Note that according to spec [5]int if full type name in this case. You can think of it as of a struct with 5 int fields. Line x := *p makes dereferencing pointer to the t (a value). Assigning value creates a copy of it. If you want to pass a "reference" to t make slice of it: t[:].

答案2

得分: -1

好的,我明白了。操作符":="用于分配一个新的内存地址。

英文:

Okay found it, the operator ":=" allocates a new memory address.

huangapple
  • 本文由 发表于 2017年3月6日 18:44:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/42623535.html
匿名

发表评论

匿名网友

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

确定