Go MinGW编译器对if-else语句报错。

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

Go MinGW compiler complains about if-else statement

问题

考虑以下(无用的)Go函数:

func domagic(n int) int {
    if n > 10 {
        return n;
    } else {
        return 0;
    }
}

这给我带来了以下编译器错误:

> main.go:15: 函数结束时没有返回语句

然而,如果我在if-else块之外返回一个值(在函数结束之前),它将编译通过而没有错误。

这种行为是设计上的,还是只是Go MinGW编译器尚未实现的功能?

英文:

Consider the following (useless) Go function:

func domagic(n int) int {
	if n > 10 {
		return n;
	} else {
		return 0;
	}
}

This gives me the following compiler error:

> main.go:15: function ends without a return statement

However, if i return a value outside the if-else block (before the end of the function), it compiles without errors.

Is this behavior by design, or is it something simply not yet implemented in the Go MinGW compiler?

答案1

得分: 2

简单地在谷歌上搜索确切的编译器错误信息会得到这个错误追踪问题。所以我不会说这是“按设计”来的,因为它看起来更像是“它只是以这种方式实现了”。还可以参考这个讨论帖子

英文:

Simple googling for the exact compiler error message yields this bugtracker issue. So I'd not say it's "by design" as it looks more like "it'd just happened to be implemented this way". See also this thread.

答案2

得分: 1

这是设计的结果。写:

package main

import "fmt"

func domagic(n int) int {
    if n > 10 {
        return n
    }
    return 0
}

func main() {
    fmt.Println(domagic(7), domagic(42))
}

输出:

0 42
英文:

It's by design. Write:

package main

import "fmt"

func domagic(n int) int {
	if n > 10 {
		return n
	}
	return 0
}

func main() {
	fmt.Println(domagic(7), domagic(42))
}

Output:

0 42

huangapple
  • 本文由 发表于 2011年11月3日 20:51:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/7995173.html
匿名

发表评论

匿名网友

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

确定