Pointers vs. values in parameters and return values

前端 未结 4 983
悲哀的现实
悲哀的现实 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:27

    Three main reasons when you would want to use method receivers as pointers:

    1. "First, and most important, does the method need to modify the receiver? If it does, the receiver must be a pointer."

    2. "Second is the consideration of efficiency. If the receiver is large, a big struct for instance, it will be much cheaper to use a pointer receiver."

    3. "Next is consistency. If some of the methods of the type must have pointer receivers, the rest should too, so the method set is consistent regardless of how the type is used"

    Reference : https://golang.org/doc/faq#methods_on_values_or_pointers

    Edit : Another important thing is to know the actual "type" that you are sending to function. The type can either be a 'value type' or 'reference type'.

    Even as slices and maps acts as references, we might want to pass them as pointers in scenarios like changing the length of the slice in the function.

提交回复
热议问题