Go struct initialization

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

Go struct initialization

问题

Go语言中为什么可以使用&PersonPerson两种方式进行初始化?

package main

import "fmt"

type Person struct {
	name string
}

func (p Person) Who() string {
	return "Person: " + p.name
}

func main() {
	var p1 = &Person{"Adam"}
	fmt.Println(p1.Who()) // Adam
	var p2 = Person{"Ben"}
	fmt.Println(p2.Who()) // Ben
}

在Go语言中,&PersonPerson两种方式都可以用来初始化结构体。使用&Person时,会创建一个指向Person类型的指针,并将结构体的字段进行初始化。而使用Person时,会直接创建一个Person类型的实例,并进行字段的初始化。两种方式最终都可以正常使用结构体的方法和字段。

英文:

How come Go can be initialized using both &Person and Person?

package main

import "fmt"

type Person struct {
	name string
}

func (p Person) Who() string {
	return "Person: " + p.name
}

func main() {
	var p1 = &Person{"Adam"}
	fmt.Println(p1.Who()) // Adam
	var p2 = Person{"Ben"}
	fmt.Println(p2.Who()) // Ben
}

答案1

得分: 5

p2 := Person{"Ben"}通过将"Ben"赋值给name来初始化一个Person结构体,并将其赋值给p2p2是一个值类型Person

p1 := &Person{"Adam"}通过将"Adam"赋值给name来初始化一个Person结构体,并将该结构体的地址赋值给p1p1是一个指针类型*Person

Who()是为值类型Person的接收器定义的方法,这意味着该功能始终接收接收实例的副本。这在可变性方面是一个重要因素。这也适用于指针句柄,例如你的示例中的p2,但接收器将继续是实例的本地副本,除非你将接收器定义更改为(p *Person),这将提供指针引用的本地副本。

英文:

p2 := Person{"Ben"} initializes a Person struct by assigning "Ben" to name, and assigned that to p2. p2 is of a value type Person.

p1 := &Person{"Adam"} initializes a Person struct by assigning "Adam" to name, and then assigns the address of that struct to p1. p1 is of a pointer type *Person.

Who() is a method defined for a receiver of value type Person, which means, the functionality always receives a copy of the receiving instance. This is an important factor when it comes to mutability. This also works with pointer handles, such as in your example with p2, but the receiver will continue to be a local copy of the instance, unless you change the receiver definition to (p *Person), which will provide a local copy of the pointer reference.

huangapple
  • 本文由 发表于 2021年6月23日 08:54:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/68092268.html
匿名

发表评论

匿名网友

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

确定