Alex Rivera | Logout

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

Asked 2013-03-11T10:12:56.707
23

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.

Edit
Report

1 Answer

3
func canFail() (card Card, err error) {
        if somethingWrong {
                err = errors.New("Not yet implemented")
                return
        }

        if foo {
                card = baz
                return
        }

        ... 

        // or 
        return Card{Ace, Spades}, nil
}
answered 2013-03-11T10:21:50.137

Your Answer