gpt4 book ai didi

go - 从另一个队列中轮询一个简单队列,并从第二个队列填充第一个队列

转载 作者:IT王子 更新时间:2023-10-29 02:29:09 27 4
gpt4 key购买 nike

换句话说,一个事件驱动队列的流程:

  • 轮询事件队列
  • 如果找到事件,则处理事件,然后是下一个轮询周期
  • 如果没有发现事件,轮询数据队列
  • 如果找到数据,推送到事件队列,开始下一个循环轮询事件队列
  • 如果没有找到数据,退出流程

代码如下:

package main

import "fmt"

type Queue struct {
stream []string
}

// Next returns first element from stream.
// Returns false if no element is in the stream.
func (q *Queue) Next() (s string, ok bool) {
if len(q.stream) == 0 {
return s, false
}
s = q.stream[0]
q.stream = q.stream[1:]
return s, true
}

func main() {
// define queues
events := []string{"event"}
q1 := &Queue{stream: events}
data := []string{"data1", "data2", "data3"}
q2 := &Queue{stream: data}

// poll first queue
for e, ok := q1.Next(); ok; e, ok = q1.Next() {
// nothing in q1
if !ok {
fmt.Println("Nothing found in q1")

// poll second queue
d, ok := q2.Next()
if !ok {
return
}

// found d in q2 and append to q1
fmt.Printf("found in q2 %v\n", d)
q1.stream = append(q1.stream, d)
return
}

// do some stuff to e ...
fmt.Printf("found in q1 %v %v\n", e, ok)
}
}

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

我得到的只是第一个队列中的元素。

found in q1 event true

代码从不轮询第二个队列并将其元素附加到第一个队列。我做错了什么?

如果我尝试

// poll first queue
for e, ok := q1.Next() {
// ...
}

编译器抛出

tmp/sandbox299553905/main.go:28:25: syntax error: e, ok := q1.Next() used as value

感谢任何提示。


更新:这是循环的解决方案。

// poll first queue
for e, ok := q1.Next(); true; e, ok = q1.Next() {
// nothing in q1
if !ok {
fmt.Println("Nothing found in q1")

// poll second queue
for d, ok := q2.Next(); true; d, ok = q2.Next() {
if !ok {
fmt.Println("Nothing found in q2. exit")
return
}

// found d in q2 and append to q1
fmt.Printf("found in q2: %v. append to q1\n", d)
q1.stream = append(q1.stream, d)
break
}
continue
}

// do some stuff to e ...
fmt.Printf("found in q1: %v. do stuff\n", e)
}

可以在 Playground 上测试https://play.golang.org/p/qo0zoBPROe .

最佳答案

当它没有找到任何东西时,你退出循环。只需将您的 for 循环更改为以下内容,但请注意,这会使循环无限,因此您必须 breakreturn 退出。

for e, ok := q1.Next(); ok || !ok ; e, ok = q1.Next() {

关于go - 从另一个队列中轮询一个简单队列,并从第二个队列填充第一个队列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45989127/

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