KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
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.
Tags (comma-separated)
Save Edits
Cancel