Pointers vs. values in parameters and return values

前端 未结 4 974
悲哀的现实
悲哀的现实 2020-11-22 06:08

In Go there are various ways to return a struct value or slice thereof. For individual ones I\'ve seen:

type MyStruct struct {
    Val int
}

fu         


        
4条回答
  •  一向
    一向 (楼主)
    2020-11-22 06:32

    A case where you generally need to return a pointer is when constructing an instance of some stateful or shareable resource. This is often done by functions prefixed with New.

    Because they represent a specific instance of something and they may need to coordinate some activity, it doesn't make a lot of sense to generate duplicated/copied structures representing the same resource -- so the returned pointer acts as the handle to the resource itself.

    Some examples:

    • func NewTLSServer(handler http.Handler) *Server -- instantiate a web server for testing
    • func Open(name string) (*File, error) -- return a file access handle

    In other cases, pointers are returned just because the structure may be too large to copy by default:

    • func NewRGBA(r Rectangle) *RGBA -- allocate an image in memory

    Alternatively, returning pointers directly could be avoided by instead returning a copy of a structure that contains the pointer internally, but maybe this isn't considered idiomatic:

    • No such examples found in the standard libraries...
    • Related question: Embedding in Go with pointer or with value

提交回复
热议问题