Which "return" is better?


(Ήαϻe̸d̨ MΌsϮαϝαe̸ΐ༄) #1

Hi there
Sorry about a simple question such this :

which “return” is performance or u usually usage? (when u have a lot of returns)

here is playGround :
https://play.golang.org/p/bKqOs70SnUB

also, below code :

A

func getInfo(a int, b string , c bool, d int ) (aa int , bb string , cc bool, dd int){
    	a = aa
    	b = bb
    	c = cc
    	d = dd
    	return
    }

B

func getInfo2(a int, b string , c bool, d int ) ( int ,string , bool,  int) {
    	
    	if "ok" == "ok" {
    		return 1, "good", true, 2
    	} 
    	
    	return 0, "", false, 0
    }

C

type InfoParameters struct {
	A int
	B string
	C bool
	D int
}
type InfoReturns struct {
	AA int
	BB string
	CC bool
	DD int
}
func getInfo3(all InfoParameters) (*InfoReturns) {
       
	if "ok" == "ok" {
		all.A = 1
		all.B = "good"
		all.C = true
		all.D = 2
		return &InfoReturns{all.A,all.B,all.C,all.D }
	}

	return nil
}

Thanks in Advance.


(Johan Dahl) #2

Hi

Interesting question. https://tour.golang.org/basics/7 just recommends A for short functions. And using C would only be recommended if the parameters form a “natural” struct and not just for putting together some parameters to a function. Performance of A and B should be equal and C could maybe be a bit slower if the struct is placed on the heap. But if this happens will depend on how it is used outside of the function.


(Michael Younkin) #3

Usually avoid A, unless you have an algorithm that is made more elegant with named return values. Most of the time, they are confusing when used in that way.

B is fine but the function will be harder to use because it has so many return values. I would avoid this as well.

C is okay if you’re trying to set it up for backwards compatibility (if you might add more return values later, and this is a library API or something like that). Otherwise I’d probably just copy the struct instead of returning a pointer.

I probably would not write a function with so many return values, unless it definitely makes sense in the context. Most of the time it will be confusing, especially if they are different types.

BTW, if you have named return values, you can do this:

func getInfo() (a string, b err) { return "hello", nil }

ie you can still use a return statement like normal. This way, the named return values can be used in deferred functions and as documentation. You’ll see this style frequently.