在错误情况下,我是否总是需要返回一个值?

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

do I always have to return a value even on error

问题

如果我有一个看起来像这样的函数:

  func ThisIsMyComplexFunc() (ComplexStruct, error)

其中ComplexStruct是一个通常包含大量值的大型结构体。

如果函数在开始之前就遇到错误,还没有开始构建结构体,我希望只返回错误,例如:

  return nil, err

但它不允许我这样做,它强制我创建一个虚拟的复杂结构体,并将其与错误一起返回,即使我从不想使用该结构体。

有没有办法解决这个问题?

英文:

If I have a function that looks like this

  func ThisIsMyComplexFunc() (ComplexStruct, error)

where ComplexStruct is a big struct that usually contain loads of values.

What if the function stumbles on an error right in the beginning, before I even started building my struct, ideally I would like to only return the error, e.g.

  return nil, err

but it wont let me do it, it forces me to create a dummy complex struct and return that together with the error, even though I never want to use the struct.

Is there a way around this?

答案1

得分: 3

如果你的函数声明要返回两个值,那么你需要返回两个值。

一个可能简化你的代码的选项是使用命名返回值:

func ThisIsMyComplexFunc() (s ComplexStruct, err error) {
    ...
}

现在你可以直接给s和/或err赋值,然后使用一个简单的return语句。你仍然会返回一个ComplexStruct值,但你不需要手动初始化它(它将默认为零值)。

英文:

If your function is declared to return two values, then you will need to return two values.

One option that might simplify your code is to use named return values:

func ThisIsMyComplexFunc() (s ComplexStruct, err error) {
    ...
}

Now you can just assign to s and/or err and then use a bare return statement. You will still be returning a ComplexStruct value, but you don't need to initialise it manually (it will default to a zero value).

答案2

得分: 2

你可以返回一个指向结构体的指针:

func ThisIsMyComplexFunc() (*ComplexStruct, error) {
  ...
  if somethingIsWrong {
    return nil, err
  }
  ...
  return &theStructIBuilt, nil
}

一般来说,通过指针传递大的结构体会更加高效,因为复制指针比复制整个结构体更容易。

英文:

You can return a pointer to the struct:

func ThisIsMyComplexFunc() (*ComplexStruct, error) {
  ...
  if somethingIsWrong {
    return nil, err
  }
  ...
  return &theStructIBuilt, nil
}

In general, it'll be cheaper to pass big structs by pointer anyway, because it's easier to copy a pointer than the whole struct.

huangapple
  • 本文由 发表于 2013年12月1日 22:31:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/20313216.html
匿名

发表评论

匿名网友

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

确定