Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the idiomatic way to return either a struct or an error?

Tags:

I have a function that returns either a Card, which is a struct type, or an error.

The problem is, how can I return from the function when an error occurs ? nil is not valid for structs and I don't have a valid zero value for my Card type.

func canFail() (card Card, err error) {
    // return nil, errors.New("Not yet implemented"); // Fails
    return Card{Ace, Spades}, errors.New("not yet implemented"); // Works, but very ugly
}

The only workaround I found is to use a *Card rather than a Card, a make it either nil when there is an error or make it point an actual Card when no error happens, but that's quite clumsy.

func canFail() (card *Card, err error) {
    return nil, errors.New("not yet implemented");
}

Is there a better way ?

EDIT : I found another way, but don't know if this is idiomatic or even good style.

func canFail() (card Card, err error) {
    return card, errors.New("not yet implemented")
}

Since card is a named return value, I can use it without initializing it. It is zeroed in its own way, I don't really care since the calling function is not supposed to use this value.

like image 371
Fabien Avatar asked Mar 11 '13 10:03

Fabien


People also ask

Should I return a struct or a pointer?

There are two ways of "returning a structure." You can return a copy of the data, or you can return a reference (pointer) to it. It's generally preferred to return (and pass around in general) a pointer, for a couple of reasons. First, copying a structure takes a lot more CPU time than copying a pointer.

Can you return a pointer to a struct in C?

Use Pointer Notation to Return struct From Function The pointer serves as a handle to the object and its size is fixed regardless of the structure stored there. Using pointers to return struct potentially reduces memory traffic and gives code more performance.


1 Answers

func canFail() (card Card, err error) {
    return card, errors.New("not yet implemented")
}

I think this, your third exampe, is fine too. The understood rule is that when a function returns an error, other return values cannot be relied upon to have meaningful values unless documentation clearly explains otherwise. So returning a perhaps meaningless struct value here is fine.

like image 62
Sonia Avatar answered Oct 03 '22 04:10

Sonia