英文:
Go struct initialization
问题
Go语言中为什么可以使用&Person
和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
}
在Go语言中,&Person
和Person
两种方式都可以用来初始化结构体。使用&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
结构体,并将其赋值给p2
。p2
是一个值类型Person
。
p1 := &Person{"Adam"}
通过将"Adam"
赋值给name
来初始化一个Person
结构体,并将该结构体的地址赋值给p1
。p1
是一个指针类型*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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论