英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论