使用语言

时间:2017-03-15 17:52:24

标签: go

是否可以用go语言创建函数管道,其中一个函数的输出直接转换为另一个函数的输入。

如果不清楚并且您需要更多信息,请在评论中讨论。

其他函数式语言提供了一些结构,例如它在带有then的javascript中的promises,在java中它们使用andThenlambdas,以及{ {1}}它是c#。像unix这样的Shell程序还提供了称为管道FunctionExtensions

的buitin方法
|

我们也可以做类似

的事情
func processA(test TestObj) {
    // do something
    return test
}

func process B(test TestObj) {
    //do something
    return test
}

func processC(test TestObj) {
    //do something
    return test
}

jim,第二个例子使用频道?能否请您使用我的代码提供代码示例。

2 个答案:

答案 0 :(得分:0)

我也不确定你想做什么,但这里是Go中链表实现的一个例子。

package main

import "fmt"

type LinkedList struct {
    value interface{}
    next  *LinkedList
}

func (oldNode *LinkedList) prepend(value interface{}) *LinkedList {
    return &LinkedList{value, oldNode}
}

func tail(value interface{}) *LinkedList {
    return &LinkedList{value, nil}
}

func traverse(ll *LinkedList) {
    if ll == nil {
        return
    }
    fmt.Println(ll.value)
    traverse(ll.next)
}

func main() {
    node := tail(5).prepend(6).prepend(7)
    traverse(node)
}

因此,正如您所看到的,chain方法可以使用所谓的fluentbuilder接口。上面的例子IMO是一个合适的地方。 https://www.martinfowler.com/bliki/FluentInterface.html

现在,如果你想做一个异步/非阻塞请求,那么我会使用channels / goroutines。它并不是一个真正的承诺,但如果你愿意,你当然可以处理成功/错误。

func NonBlockingGet(url string) <-chan []byte {
    c := make(chan []byte, 1)

    go func() {
        var body []byte
        defer func() {
            c <- body
        }()

        res, err := http.Get(url)
        if err != nil {
            return
        }
        defer res.Body.Close()

        body, _ = ioutil.ReadAll(res.Body)
    }()

    return c
}

func main() {
    promise := NonBlockingGet("http://example.com")

    // can do other stuff here - because doing a non-blocking get request.
    log.Println("This will output before the response length")

    body := <- promise // Will wait here till promise is resolved.
    log.Printf("response length: %d", len(body))
}

我希望这会有所帮助。正如上面的评论所说,这不是javascript,我们不应该尝试。但是,您可以随时将<- promise作为参数传递给函数,而不是将body分配给<- promise

答案 1 :(得分:0)

我也在寻找这种模式,但没有运气。这在其他语言中很常见,但在golang中却不是

无论如何,您可能会发现此实用https://github.com/open-zhy/fn-pipe

它基本上使用reflection来通过函数映射所有输入和输出