gpt4 book ai didi

go - 在结构中取消引用指向 DB 的指针

转载 作者:IT王子 更新时间:2023-10-29 02:05:55 25 4
gpt4 key购买 nike

通常,当我看到在结构上声明的字段时,它没有指针或取消引用的指针符号 *,但是在几个代码片段中,我看到结构中的数据库字段带有指针取消引用,如下所示。为什么有必要?

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
}

最佳答案

or a dereferenced pointer symbol *

这是规范,对于复杂的非值类型,为了避免复制。
参见 Golang book "Pointers"例如其中带有指针的结构。

return &DB{db}

返回指向新创建的 DB 实例的指针。
如“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

来自“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


有关更多信息,请参阅“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.

关于go - 在结构中取消引用指向 DB 的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25450690/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com