英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论