摆脱无用的退货声明

JDo*_*981 5 loops return return-value go

我试图重构一些代码并使其更容易阅读.我注意到在一些函数的末尾我有一些不必要的return语句.这是一个概念性示例:

func someFunction(a []arr) int {
    for _,v := range a {
        if v == something {
            // will defenitly get here at some point! 
            return somethingElse
        }
    }
    return -1 // never ever happens! 
} 
Run Code Online (Sandbox Code Playgroud)

在我看来,函数结尾处的return语句具有误导性,因为它表明它可能在某个时候达到.我该如何预防呢?

请注意,我在其他方面进行错误处理,这就是为什么我可以肯定,someFunction它将永远返回somethingElse.

Jak*_*vec 10

恐慌而不是在函数结束时返回假值:

func someFunction(a []arr) int {
    for _,v := range a {
        if v == something {
            // will defenitly get here at some point! 
            return somethingElse
        }
    }

    panic("unreachable")
} 
Run Code Online (Sandbox Code Playgroud)

这是标准库中的常见模式.

  • 就是这个.任何不可能的地方都应该恐慌.如果函数以恐慌结束,Go编译器甚至会接受缺少的返回. (2认同)