英文:
dereference pointer to DB in struct
问题
通常情况下,当我看到在结构体上声明一个字段时,它通常没有指针或解引用指针符号*。然而,在我看到的一些代码片段中,当在结构体中看到一个数据库字段时,它会使用指针解引用,就像你下面看到的那样。为什么这是必要的?
type DB struct {
*bolt.DB
}
func Open(path string, mode os.FileMode) (*DB, error) {
db, err := bolt.Open(path, mode)
if err != nil {
return nil, err
}
return &DB{db}, nil
}
英文:
Usually when I see a field declared on a struct it's without a pointer or a dereferenced pointer symbol *, however in several code snippets where I've seen a database field in a struct it's with a pointer dereference as you see below. Why is that necessary?
type DB struct {
*bolt.DB
}
func Open(path string, mode os.FileMode) (*DB, error) {
db, err := bolt.Open(path, mode)
if err != nil {
return nil, err
}
return &DB{db}, nil
}
答案1
得分: 2
> 或者一个解引用指针符号 *
这是一种常见的做法,用于复杂的非值类型,以避免进行复制操作。
参见Golang书籍《指针》中包含指针的结构体示例。
return &DB{db}
这将返回一个指向新创建的DB
实例的指针。
正如在“你可以用Go“固定”一个对象在内存中吗?”中所指出的:
> 请注意,与C语言不同,返回局部变量的地址是完全可以的;变量关联的存储在函数返回后仍然存在。
从“指针/值的微妙之处”中:
> Go也是按值传递的,但它同时具有指针和值类型。指针引用特定的内存位置,并允许您更改该位置上的数据。
更多信息,请参见“在Go中最佳实践“返回”结构体?”
> 对于大型结构体或需要更改的结构体,请使用指针;否则,请使用值,因为通过指针意外更改事物会令人困惑。
英文:
> or a dereferenced pointer symbol *
That is the norm, for complex non-value type, in order to avoid making a copy.
See Golang book "Pointers" for example of struct with pointer(s) in them.
return &DB{db}
That returns a pointer to the newly created DB
instance.
As noted in "Can you “pin” an object in memory with Go?":
> Note that, unlike in C, it's perfectly OK to return the address of a local variable; the storage associated with the variable survives after the function returns
From "Pointer/Value Subtleties":
> Go is also pass by value, but it has both pointers and value types. Pointers refer to a certain memory location, and allow you to mutate the data at that location
For more, see "Best practice “returning” structs in Go?"
> Use pointers for big structs or structs you'll have to change, and otherwise use values, because getting things changed by surprise via a pointer is confusing.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论