英文:
Why am I getting a missing return at end of function in this code?
问题
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
语句,我就不会得到这个错误。我错在哪里?
英文:
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"
}
In the first if
statement, I get an error of missing return at end of function error. I don't get this error if I remove the else if
statement. Where am I going wrong?
答案1
得分: 3
你之所以会遇到这个错误,是因为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"
}
英文:
You get this error because else
statement must be on the same line as the closing }
of the first condition.
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"
}
答案2
得分: 1
由于您在第一个if
语句中有一个返回语句,您可以直接省略else
语句。如果满足第一个条件,第二个if
语句将不会被执行。
func getKeyNameFromDeploymentAndSubnet(subnetType SubnetType, deploymentType DeploymentType, keyNameMap map[SubnetType]string) string {
if (deploymentType == NoDeployment || deploymentType == PDBAWindows || deploymentType == AgentDeployment) {
return keyNameMap[subnetType]
}
if (deploymentType == AnsibleDeployment) {
return "bar"
}
return "foo"
}
英文:
Since you have a return statement in your first if
, you may just drop the else
statement. The second if
is not going to be reached anyway if the first ones conditions are met.
func getKeyNameFromDeploymentAndSubnet(subnetType SubnetType, deploymentType DeploymentType, keyNameMap map[SubnetType]string) string {
if (deploymentType == NoDeployment || deploymentType == PDBAWindows || deploymentType == AgentDeployment) {
return keyNameMap[subnetType]
}
if (deploymentType == AnsibleDeployment) {
return "bar"
}
return "foo"
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论