如何指定多个返回值的类型

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

How to specify the types of multiple return values

问题

有时候,当一个函数返回多个值且它们的类型没有指定时,我发现Go代码很难阅读。这种情况是否可能?请看下面的例子:

func randomNumber()(int, error) {
    return 4, nil 
}

func main() {
    nr, err := randomNumber()
    // 我想要的方式:
    // var nr int, err error = randomNumber()
}
英文:

Sometimes i find Go code hard to read when a function returns multiple values and their types are not specified. Is this possible ? See below:

func randomNumber()(int, error) {
	return 4, nil 
}

func main() {
	nr, err := randomNumber()
	// What i would like to do:
	// var nr int, err error = randomNumber()
}

答案1

得分: 4

不,这是不可能的。但是,你可以提前定义变量,这样会更容易理解一些。

func randomNumber()(int, error) {
    return 4, nil 
}

func main() {
    var nr int
    var err error
    // 注意使用的是'='而不是':='
    nr, err = randomNumber()
}
英文:

No, that's not possible. However, you could define the variables ahead of time to make it a little easier to follow.

func randomNumber()(int, error) {
    return 4, nil 
}

func main() {
    var nr int
    var err error
    // Note the '=' instead of ':='
    nr, err = randomNumber()
}

huangapple
  • 本文由 发表于 2013年3月20日 06:27:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/15511722.html
匿名

发表评论

匿名网友

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

确定