指针还是复制

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

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
*/

huangapple
  • 本文由 发表于 2021年8月13日 22:41:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/68774220.html
匿名

发表评论

匿名网友

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

确定