dtbi27903 2014-08-22 15:36
浏览 93
已采纳

解引用指向结构体中DB的指针

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条回答 默认 最新

  • dongliu1883 2014-08-22 15:51
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 各位佬,下面的问题怎么用python实现?
  • ¥15 CCF-CSP 2023 第三题 解压缩(50%)
  • ¥30 comfyui openpose报错
  • ¥20 Wpf Datarid单元格闪烁效果的实现
  • ¥15 图像分割、图像边缘提取
  • ¥15 sqlserver执行存储过程报错
  • ¥100 nuxt、uniapp、ruoyi-vue 相关发布问题
  • ¥15 浮窗和全屏应用同时存在,全屏应用输入法无法弹出
  • ¥100 matlab2009 32位一直初始化
  • ¥15 Expected type 'str | PathLike[str]…… bytes' instead