Aeonitis
Aeonitis

Reputation: 5897

Error handling with Go, Best Practice on returns

Should I use an enum for the return values, throw an exception, I have to return something and returning 100 is not the right answer. I'm also not great at golang yet...

The ideal result should only really be 1, -1, or 0. That additional return forced on me must be a sign that I am missing something.

func compare(A string, B string) (int, error, error) {
    for index := range 10 {

        // Return results before end of permutation if possible
        if A > B {
            return 1, errA, errB
        } else if A < B {
            return -1, errA, errB
        } else {
            // If we're at the last elements and both are equal
            if index == 10 {
                return 0, errA, errB
            }
        }

    }

    // How should I handle this?I have to return something. No?
    return -100, nil, nil
}

Upvotes: 0

Views: 723

Answers (1)

Gregor Zurowski
Gregor Zurowski

Reputation: 2346

Move the last else block further down and make it the default return statement:

func compare(A string, B string) (int, error, error) {
    for index := range 10 {
        // Return results before end of permutation if possible
        if A > B {
            return 1, errA, errB
        } else if A < B {
            return -1, errA, errB
        }
    }

    return 0, nil, nil
}

Upvotes: 2

Related Questions