我有一个简单的应用程序,我正在阅读MongoDB的复制oplog,将结果序列化为Go结构并将其发送到要处理的通道.目前我正在从该频道阅读并简单地打印出结构内部的值.
我尝试使用for/range读取通道中的值,直接从中读取简单的值,并将其置于带超时的select中.结果都是一样的.每次运行代码时,我都会从频道获得不同的结果.我每次都会看到频道被写入一次但是从该频道读取有时我会读出相同的值1-3,有时甚至是4次,即使只有一次写入.
这通常仅在初始加载时发生(拉入较旧的记录),并且在读取对通道的实时添加时似乎不会发生.是否存在一些问题,即在第一次读取该项目之前,从该频道读取的速度过快发生?
package main
import (
"fmt"
"labix.org/v2/mgo"
"labix.org/v2/mgo/bson"
)
type Operation struct {
Id int64 `bson:"h" json:"id"`
Operator string `bson:"op" json:"operator"`
Namespace string `bson:"ns" json:"namespace"`
Select bson.M `bson:"o" json:"select"`
Update bson.M `bson:"o2" json:"update"`
Timestamp int64 `bson:"ts" json:"timestamp"`
}
func Tail(collection *mgo.Collection, Out chan<- *Operation) {
iter := collection.Find(nil).Tail(-1)
var oper *Operation
for {
for iter.Next(&oper) {
fmt.Println("\n<<", oper.Id)
Out <- oper
}
if err := iter.Close(); err != nil {
fmt.Println(err)
return
}
}
}
func main() { …Run Code Online (Sandbox Code Playgroud) 我有一个for循环连续运行一段时间,但我只是将它用作我想要每10分钟运行一次的函数.如何声明这个for循环而不必在循环内部的某处使用'x'
interval := time.Tick(10 * time.Minute)
for x := range interval {
...code that does not use x
}
Run Code Online (Sandbox Code Playgroud)
我已经尝试重构for循环但没有任何结果导致它运行而没有专门使用'x',我知道我可以简单地在循环内部用'x'做一些事情,但我宁愿学习如何正确地实现这个for循环然后做一个黑客.