【问题标题】:Error handling with Go, Best Practice on returnsGo 的错误处理,退货的最佳实践
【发布时间】:2021-08-05 16:14:22
【问题描述】:

我是否应该使用枚举作为返回值,抛出异常,我必须返回一些东西,而返回 100 不是正确的答案。我也不太擅长 golang...

理想的结果应该只有 1、-1 或 0。强加给我的额外回报一定表明我错过了什么。

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
}

【问题讨论】:

  • 你能解释一下你想要做什么吗?比如为什么你有一个 for 循环?
  • 您可以将“等于”作为默认结果,并将0 的返回值放在循环之后。换句话说,循环检查不等式并提前返回,否则它将结束循环并返回相等。

标签: go if-statement exception error-handling return


【解决方案1】:

将最后一个 else 块进一步向下移动并使其成为默认返回语句:

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
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-12
    • 2017-11-26
    • 2019-10-28
    • 2011-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多