为什么在Go语言中要先解引用再引用呢?

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

Why dereference only to reference again in Go

问题

gorilla/sessions中,有以下的代码:

func (s *CookieStore) New(r *http.Request, name string) (*Session, error) {
	session := NewSession(s, name)
	opts := *s.Options
	session.Options = &opts
    ...

其中s.Options的类型是*sessions.Options

type CookieStore struct {
	...
	Options *Options // 默认配置
}

sessios.Session.Options也是*sessions.Options类型:

type Session struct {
	...
	Options *Options
	...
}

我的问题是,为什么要对s.Options进行解引用,然后将其引用赋值给session.Options?为什么不直接这样做:

func (s *CookieStore) New(r *http.Request, name string) (*Session, error) {
	session := NewSession(s, name)
	session.Options = s.Options
    ...

这样做是为了确保将s.Options的解引用值复制到session.Options中,而不是实际的引用,从而避免两个对象指向同一内容。

英文:

In gorilla/sessions there is the following code:

func (s *CookieStore) New(r *http.Request, name string) (*Session, error) {
	session := NewSession(s, name)
	opts := *s.Options
	session.Options = &opts
    ...

Where s.Options is of type *sessions.Options:

type CookieStore struct {
	...
	Options *Options // default configuration
}

And sessios.Session.Options is also of type *sessions.Options:

type Session struct {
	...
	Options *Options
	...
}

My question is, what is the point of dereferencing s.Options and then assigning its reference to session.Options? Why not just do:

func (s *CookieStore) New(r *http.Request, name string) (*Session, error) {
	session := NewSession(s, name)
	session.Options = s.Options
    ...

Is this to make sure the dereferenced value of s.Options is copied over to session.Options, and not the actual reference therefore avoiding both objects pointing to the same thing?

答案1

得分: 4

这是为了防止两个指针指向同一位置。

session := NewSession(s, name)
opts := *s.Options

此时,opts 包含了 s.Options 的副本。然后:

session.Options = &opts

这将把 session.Options 设置为一个与 s.Options 不同的选项对象,但其内容是从 s.Options 初始化的。

英文:

It is to prevent two pointers from pointing to the same location.

session := NewSession(s, name)
opts := *s.Options

At this point, opts contains a copy of s.Options. Then:

session.Options = &opts

This will set session.Options to an options object that is different from s.Options, but whose contents are initialized from s.Options.

huangapple
  • 本文由 发表于 2021年11月14日 12:01:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/69960185.html
匿名

发表评论

匿名网友

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

确定