Golang的引用传递

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

Golang call by reference

问题

我想理解Golang中的按引用调用。我写了这段代码。当我打印地址(在main函数中的第一个地址和在printPointer函数中的第二个地址)时,它们看起来不同。请帮助我更好地理解。

package main

import "fmt"

type person struct{
  name string
  id string
}

func main() {
  // 结构体
  c := person{name: "vijay", id: "1234"}
  fmt.Println(&c)
  printPointer(&c)
  fmt.Println(c)
}

func printPointer(p *person) {
  (*p).name = "Sree"
  fmt.Println(&p)
}
英文:

I want to understand golang call by reference.I wrote this piece of code. When I print both the address(1st address in main and 2nd address in printPointer, it looks different).Please help to understand better.

package main

import "fmt"

type person struct{
 name string
 id string
}

func main() {
//struct
 c := person{name: "vijay", id: "1234",}
 fmt.Println(&c)
 printPointer(&c)
 fmt.Println(c)

}

func printPointer(p *person) {
 (*p).name = "Sree"
fmt.Println(&p)
}

答案1

得分: 4

在Go语言中,所有的参数都是按值传递的。因此:

fmt.Println(c)

这里接收的是c的一个副本。

fmt.Println(&c)

这里接收的是&c的一个副本。

在你的代码中,printPointer函数接收的是&c的一个副本作为p。当你打印&p时,你打印的是那个副本的地址,而不是&c的地址。

使用fmt.Println(p)即可。

英文:

In go, all arguments are passed by value. Thus:

fmt.Println(c)

This receives a copy of c

fmt.Println(&c)

This received a copy of &c.

In your code, printPointer receives a copy of &c as p. When you print &p, you print the address of that copy, not &c.

Use fmt.Println(p).

答案2

得分: 0

printPointer函数中,你打印的是&p的值,或者说是“指向p的指针”。p的类型是*person,或者说是“指向person的指针”。因此,你实际上打印的值是“指向指针的指针”,我认为这不是你的意图。

尝试只打印p

英文:

In printPointer, you're printing the value &p, or "pointer to p". p is of type *person, or "pointer to person". Thus, the value you're actually printing is of type "pointer to pointer to person" which I don't think is your intention.

Try printing just p.

huangapple
  • 本文由 发表于 2021年6月7日 00:09:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/67861173.html
匿名

发表评论

匿名网友

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

确定