英文:
Pointer or copy
问题
我有以下的Go代码:
type Logger struct {
Endpoint string
}
type Client struct {
Logger Logger
}
func (c *Client) DoSomethingAwesome() {
scopedLogger := c.Logger
scopedLogger.LogSomethingAwesome()
}
我无法确定我创建的scopedLogger
变量是一个新实例还是指向相同的Logger
实例。
英文:
I have the following Go code:
type Logger struct {
Endpoint string
}
type Client struct {
Logger Logger
}
func (c *Client) DoSomethingAwesome() {
scopedLogger := c.Logger
scopedLogger.LogSomethingAwesome()
}
And I cannot figure out if the scopedLogger
variable that I am creating is a new instance or is it pointing to the same Logger
?
答案1
得分: 2
这是一个新的日志记录器实例。如果你想指向同一个日志记录器,请使用指针。
func (c *Client) DoSomethingAwesome() {
scopedLogger := &c.Logger
scopedLogger.LogSomethingAwesome()
}
英文:
That's a new instance of the logger. If you want to point to the same Logger use pointer
func (c *Client) DoSomethingAwesome() {
scopedLogger := &c.Logger
scopedLogger.LogSomethingAwesome()
}
答案2
得分: 0
这是一个新的实例,你可以通过打印每个变量的内存地址来验证。
package main
import "fmt"
type Logger struct {
Endpoint string
}
type Client struct {
Logger Logger
}
func (c *Client) DoSomethingAwesome() {
scopedLogger := c.Logger
p1 := &scopedLogger
// 打印指针
fmt.Printf("p1: %p\n", p1)
}
func main() {
cli := &Client{
Logger: Logger{
Endpoint: "something",
},
}
p2 := &cli.Logger
// 打印指针
fmt.Printf("p2: %p\n", p2)
cli.DoSomethingAwesome()
}
/* 输出
p2: 0xc000096220
p1: 0xc000096230
*/
英文:
its a new instance you can verify that by printing memory address of each variable.
package main
import "fmt"
type Logger struct {
Endpoint string
}
type Client struct {
Logger Logger
}
func (c *Client) DoSomethingAwesome() {
scopedLogger := c.Logger
p1 := &scopedLogger
// print pointer
fmt.Printf("p1: %p\n", p1)
}
func main() {
cli := &Client{
Logger: Logger{
Endpoint: "something",
},
}
p2 := &cli.Logger
// print pointer
fmt.Printf("p2: %p\n", p2)
cli.DoSomethingAwesome()
}
/* output
p2: 0xc000096220
p1: 0xc000096230
*/
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论