Golang if/else 无法编译。

huangapple go评论74阅读模式
英文:

Golang if/else not compiling

问题

我无法弄清楚为什么这段代码无法编译。
它显示函数结束时没有返回语句,但是当我在else后面添加了一个return语句后,它仍然无法编译。

func (d Foo) primaryOptions() []string{

	if(d.Line == 1){
		return []string{"me", "my"}
	}
	else{
		return []string{"mee", "myy"}
	}
}

我无法提供代码翻译服务,但是你可以尝试检查以下几点:

  1. 确保函数的返回类型与函数声明中的返回类型匹配。
  2. 确保在每个可能的执行路径上都有返回语句。
  3. 检查是否有其他语法错误导致编译失败。

希望这些提示对你有帮助!

英文:

I cannot figure out why this will not compile.
It says functions ends without a return statement, but when I add a return after the else, it still won't compile.

func (d Foo) primaryOptions() []string{

if(d.Line == 1){
	return []string{"me", "my"}
}
else{
	return []string{"mee", "myy"}
}
}

答案1

得分: 9

Go语言要求elseif的大括号在同一行,这是因为它的“自动分号插入”规则。

所以代码应该是这样的:

if d.Line == 1 {
    return []string{"me", "my"}
} else { // <---------------------- 这里必须放在上面
    return []string{"mee", "myy"}
}

否则,编译器会自动为你插入一个分号:

if d.Line == 1 {
    return []string{"me", "my"}
}; // <--------------------------- 如果你把它放在下面,编译器会自动插入分号
else {
    return []string{"mee", "myy"}
}

这就是你遇到错误的原因。我会马上给你提供相关文档的链接。

编辑:Effective Go中有相关信息。

英文:

Go forces else to be on the same line as the if brace.. because of its "auto-semicolon-insertion" rules.

So it must be this:

if(d.Line == 1) {
    return []string{&quot;me&quot;, &quot;my&quot;}
} else { // &lt;---------------------- this must be up here
    return []string{&quot;mee&quot;, &quot;myy&quot;}
}

Otherwise, the compiler inserts a semicolon for you:

if(d.Line == 1) {
    return []string{&quot;me&quot;, &quot;my&quot;}
}; // &lt;---------------------------the compiler does this automatically if you put it below
else {
    return []string{&quot;mee&quot;, &quot;myy&quot;}
}

..hence your error. I will link to the relevant documentation shortly.

EDIT: Effective Go has information regarding this.

huangapple
  • 本文由 发表于 2014年6月17日 11:15:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/24255189.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定