gpt4 book ai didi

go - 菊花链输入,输出 channel 一起在golang中

转载 作者:数据小太阳 更新时间:2023-10-29 03:47:16 27 4
gpt4 key购买 nike

我有以下接口(interface)和结构

type PiplineStep interface {
Do(ctx context.Context, in <-chan Message) (<-chan Message, <-chan error, error)
}

type Pipline struct {
Steps []core.PiplineStep
}

现在我正在尝试菊花接口(interface)来创建如下所示的管道

    for _, step := range p.Steps {
out, errc, err := step.Do(ctx, out)
errcList = append(errcList, errc)

if err != nil {
errc <- err
return
}

select {
case outer <- msg:
case <-ctx.Done():
return
}
}

但是编译器说不,这可能吗?

我收到以下错误“out declared and not used”我已尝试遵循,但似乎所有步骤都收到相同的 chan

    for _, step := range p.Steps {
var tmpOut <-chan core.Message
tmpOut = out
tmpOut, errcTmp, err := step.Do(ctx, tmpOut)
errcList = append(errcList, errcTmp)

if err != nil {
errc <- err
return
}
select {
case out <- msg:
case <-ctx.Done():
return
}
}

最佳答案

如果你想在每次迭代中重复使用它,你必须在循环外声明你的 channel 变量(为简洁起见省略了错误和上下文):

package main

import "fmt"

func main() {
var pipeline Pipeline

pipeline.Steps = append(pipeline.Steps,
AddBang{},
AddBang{},
AddBang{},
)

src := make(chan Message)
pipe := src

for _, s := range pipeline.Steps {
pipe = s.Do(pipe)
}

go func() {
src <- "msg 1"
src <- "msg 2"
src <- "msg 3"
}()

fmt.Println(<-pipe)
fmt.Println(<-pipe)
fmt.Println(<-pipe)
}

type Message string

type Pipeline struct {
Steps []PipelineStep
}

type PipelineStep interface {
Do(in chan Message) chan Message
}

type AddBang struct{}

func (AddBang) Do(in chan Message) chan Message {
out := make(chan Message)
go func() {
defer close(out)
for m := range in {
out <- m + "!"
}
}()
return out
}

在 Playground 上试试:https://play.golang.org/p/ItVLUBRpNA1

关于go - 菊花链输入,输出 channel 一起在golang中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49535869/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com