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.

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

报告相同问题?