douxing9228 2017-07-22 15:50
浏览 22
已采纳

Go函数点表示法

I want to build this:

finalResult, err := Function1(whatever type)
    .Function2(whatever type)
    .Function3(whatever type)

Something similar to promises in javascript but not necessarily the same concepts. Or similar to nested methods in Java. I just pretend avoid more code for the same tasks.

I don't want to do this :

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 {...}

I've been trying with several options with structs and interfaces but I can't get any result.

My apology if I have a mistake in my grammar. I'm not still so good with my skill English.

Thanks,

David

  • 写回答

2条回答 默认 最新

  • dsjq62428 2017-07-22 16:56
    关注

    I think you mean the Fluent API design pattern. You return the same Object, or struct in Go, over and over.

    This pattern does not allow you to return a tuple, or multiple return types though. You can only return one object.

    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)
    }
    

    Edit: sberry's answer had a good idea. Add an Error state on the Object struct itself which could allow u to check for errors in each func call.


    Since you are new, please remember to evaluate all answers and mark the best one you believe lead you the answer.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题