我想构建这个:
finalResult, err := Function1(whatever type)
.Function2(whatever type)
.Function3(whatever type)
类似于 javascript 中的 promise ,但不一定是相同的概念。或者类似于 Java 中的嵌套方法。我只是假装避免为相同的任务编写更多代码。
我不想这样做:
result, err := new(Function1(whatever type)) //or *Function1(whatever type)
if err != nil {...}
result1, err := result.Function2(whatever type)
if err != nil {...}
finalResult, err := result1.Function3(whatever type)
if err != nil {...}
我一直在尝试使用结构和接口(interface)的几个选项,但我得不到任何结果。
如果我的语法有误,我深表歉意。我的英语水平还不是很好。
谢谢,
大卫
最佳答案
我认为您指的是 Fluent API 设计模式。您一遍又一遍地返回相同的对象或 Go 中的结构。
尽管这种模式不允许您返回一个元组或多个返回类型。您只能返回一个对象。
https://play.golang.org/p/9PceZwi1a3
package main
import (
"fmt"
)
type Object struct {
Value string
Error error
}
func (o *Object) Before(s string) *Object {
o.Value = s + o.Value
// add an error if you like
// o.Error = error.New(...)
return o
}
func (o *Object) After(s string) *Object {
// could check for errors too
if o.Error != nil {
o.Value = o.Value + s
}
return o
}
func main() {
x := Object{}
x.
Before("123").
After("456").
After("789").
Before("0")
if x.Error != nil {
// handle error
}
fmt.Println(x.Value)
}
编辑:sberry 的回答有一个好主意。在 Object
结构本身上添加错误状态,这可以让您检查每个 func 调用中的错误。
由于您是新手,请记住评估所有答案并标记您认为最能引导您找到答案的答案。
关于Go函数点符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45256433/