when to return a pointer
tags: learning go programming
content
- when returning large struct, return a pointer instead to avoid expensive copying
- when the function might return
nil- the function is always expected to return
(MyType, error), returningnilforMyTypeis not allowed - if the function is expected to return
(*MyType, error), returningnilfor*MyTypeis allowed
- the function is always expected to return
func myFunc() (MyType, error) {
myVar, err := doSomething()
if err != nil { return nil, err} // this line is NOT allowed
return myVar
}
func myFunc2() (*MyType, error) {
myVar, err := doSomething()
if err != nil { return nil, err} // this line is allowed
return &myVar
}- when the original value would be modified later