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

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

How to specify the types of multiple return values

问题

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

  1. func randomNumber()(int, error) {
  2. return 4, nil
  3. }
  4. func main() {
  5. nr, err := randomNumber()
  6. // 我想要的方式:
  7. // var nr int, err error = randomNumber()
  8. }
英文:

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:

  1. func randomNumber()(int, error) {
  2. return 4, nil
  3. }
  4. func main() {
  5. nr, err := randomNumber()
  6. // What i would like to do:
  7. // var nr int, err error = randomNumber()
  8. }

答案1

得分: 4

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

  1. func randomNumber()(int, error) {
  2. return 4, nil
  3. }
  4. func main() {
  5. var nr int
  6. var err error
  7. // 注意使用的是'='而不是':='
  8. nr, err = randomNumber()
  9. }
英文:

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

  1. func randomNumber()(int, error) {
  2. return 4, nil
  3. }
  4. func main() {
  5. var nr int
  6. var err error
  7. // Note the '=' instead of ':='
  8. nr, err = randomNumber()
  9. }

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:

确定