一尘不染

为什么在此代码的函数结尾处缺少返回值?

go

func getKeyNameFromDeploymentAndSubnet(subnetType SubnetType, deploymentType DeploymentType, keyNameMap map[SubnetType]string) string {
    if (deploymentType == NoDeployment || deploymentType == PDBAWindows || deploymentType == AgentDeployment) {
        return keyNameMap[subnetType]
    }
    else if (deploymentType == AnsibleDeployment) {
        return "bar"
    }
    return "foo"
}

在第一条if语句中,我收到一个错误,即在函数错误结束时缺少返回。如果删除该else if语句,我不会收到此错误。我要去哪里错了?


阅读 215

收藏
2020-07-02

共1个答案

一尘不染

之所以会出现此错误,是因为else语句必须}与第一个条件的结束处在同一行。

func getKeyNameFromDeploymentAndSubnet(subnetType SubnetType, deploymentType DeploymentType, keyNameMap map[SubnetType]string) string {
    if deploymentType == NoDeployment || deploymentType == PDBAWindows || deploymentType == AgentDeployment {
        return keyNameMap[subnetType]
    } else if deploymentType == AnsibleDeployment {
        return "bar"
    }
    return "foo"
}
2020-07-02