返回值缺少Go类型

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

missing go type for returned values

问题

为什么对于以下代码没有发出警告?

$ cat ret.go
package main
import "fmt"
func foobar(x int, y int) (z, w int) {
    if x+y > 100 {
         _,w = 3,5
    } else {
        _,w = "MMM",9
    }
    return z,w
}

func main() {
    var x int
    _,x = foobar(42,13)
    fmt.Println(x)
}
$ go build -gcflags=-l ret.go

至少,Go编译器应该知道z的大小,对吗?

英文:

How come no warnings are issued for the following code?

$ cat ret.go
package main
import "fmt"
func foobar(x int, y int) (z, w int) {
    if x+y > 100 {
         _,w = 3,5
    } else {
        _,w = "MMM",9
    }
    return z,w
}

func main() {
    var x int
    _,x = foobar(42,13)
	fmt.Println(x)
}
$ go build -gcflags=-l ret.go

For the least, the go compiler should know the size of z right?

答案1

得分: 2

在Go语言中,你可以像下面这样在一行中定义多个变量:

var identifier1, identifier2 type

所以,在这里zw都被声明为int类型。

另外,参考这个链接

在Go语言中,函数的返回值可以被命名

那么,如果你没有给z赋值,它将具有int类型的默认值,即0。所以,没有警告,代码是正确的。

英文:

In golang, you can define multiple variable in one line like next:

var identifier1, identifier2 type

So, z, w here both declared as int.

Additional, see this:

> The return values of a function can be named in Golang

Then, if you not assign a value to z, it will has a default value of int, that is 0. So, no warning, the code is ok.

huangapple
  • 本文由 发表于 2021年7月21日 13:22:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/68464347.html
匿名

发表评论

匿名网友

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

确定