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), returning nil for MyType is not allowed
    • if the function is expected to return (*MyType, error), returning nil for *MyType is allowed
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

up

down

reference