在Go语言中,有没有一种方法可以组合可能失败的操作?

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

Is there a way to compose potentially failing operations in Go?

问题

我读到的大多数Go代码中都包含以下模式的频繁出现:

result1, err := failingOp1()
if err != nil {
    return err
}
dependingResult, err := failingOp2(result1)
if err != nil {
    return err
}
// 使用dependingResult进行操作

在函数式编程中,我们有Either单子及其类似物(例如Scala的Try),可以帮助我们组合失败的操作,而不需要不断重复自己。

是否有Go的等效方法可以帮助简化代码?

英文:

Most go code I read contains frequent occurrences of the following pattern:

result1, err := failingOp1()
if err != nil {
    return err
}
dependingResult, err := failingOp2(result1)
if err != nil {
    return err
}
// do stuff with dependingResult

In functional programming we have the Either monad and its cousins (e.g. Scala's Try) that allow us to compose failing operations without constantly repeating ourselves.

Is there a go equivalent that helps decluttering the code?

答案1

得分: 1

阅读更多资料后,特别是这个 Stack Overflow 回答,似乎惯用的 Go 语言偏向于在调用处处理错误,而不是向上传播潜在的错误(这是单子方法所偏好的方式)。

按照这种思路:

func wrapFailingOp1() ResultType {
  result1, err := failingOp1()
  if err != nil {
    return defaultRTOrPanic()
  }
  return result1
}

func wrapFailingOp2(result1 ResultType) DependingResultType {
    dependingResult, err := failingOp2(result1)
    if err != nil {
        return defaultDRTOrPanic()
    }
    return dependingResult
}

x := wrapFailingOp1()
y := wrapFailingOp2(x)
英文:

Reading up a bit further, in particular this SO answer, it seems idiomatic go prefers handling errors at the call-site rather than propagating the potential error upwards (which the monadic approach favours).

Following this line of thinking:

func wrapFailingOp1() ResultType {
  result1, err := failingOp1()
  if err != nil {
    return defaultRTOrPanic()
  }
  return result1
}

func wrapFailingOp2(result1 ResultType) DependingResultType {
    dependingResult, err := failingOp2(result1)
    if err != nil {
        return defaultDRTOrPanic()
    }
    return dependingResult
}

x := wrapFailingOp1()
y := wrapFailingOp2(x)

huangapple
  • 本文由 发表于 2017年3月24日 18:55:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/42997668.html
匿名

发表评论

匿名网友

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

确定