gpt4 book ai didi

pointers - [Golang]调用指针类型的方法,使用point类型和struct类型的区别?

转载 作者:IT王子 更新时间:2023-10-29 01:43:11 26 4
gpt4 key购买 nike

如标题所述,我不知道在调用方法 Greeting() 时使用结构类型或指针类型时有什么不同,在我的例子中,调用 p。 Greeting()u.Greeting() 一样吗?在调用 Greeting() 方法时,性能似乎也没有什么不同。

我认为 u.Greeting() 会自动转换为 (&u).Greeting()

Everything in Go is passed by value ,但我认为在这种情况下,调用者 u 是通过引用或指针传递的。

package main

import "fmt"

type User struct {
Name string
}

func (u *User) Greeting() string {
u.Name = u.Name+" modify"
return fmt.Sprintf("Greetings %s!", u.Name)
}

func main() {
p := &User{"cppgohan by pointer"}
u := User{"cppgohan by value"}

fmt.Println(p.Greeting(), p)
fmt.Println(u.Greeting(), u)
}

输出:

Greetings cppgohan by pointer modify! &{cppgohan by pointer modify}
Greetings cppgohan by value modify! {cppgohan by value modify}

最佳答案

对于p,调用Greeting()就是调用p.Greeting(),对于u,它是调用 (&u).Greeting()

Example :

func (u *User) Greeting() string {
return fmt.Sprintf("Greetings %s [%p]!", u.Name, u)
}

func main() {
p := &User{"cppgohan by pointer"}
u := User{"cppgohan by value"}
pu := &u

fmt.Printf("[%p] %v %v\n", pu, pu.Greeting(), pu)
fmt.Printf("[%p] %v %v\n", &u, u.Greeting(), u)
fmt.Printf("[%p] %v %v\n", p, p.Greeting(), p)
}

输出:

[0x1030e0e0] Greetings cppgohan by value [0x1030e0e0]! &{cppgohan by value}

[0x1030e0e0] Greetings cppgohan by value [0x1030e0e0]! {cppgohan by value}

[0x1030e0d8] Greetings cppgohan by pointer [0x1030e0d8]! &{cppgohan by pointer}

请注意前 2 个具有相同的地址,因为它被隐式转换为指针。

关于pointers - [Golang]调用指针类型的方法,使用point类型和struct类型的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24894479/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com