Golang,在通道上运行范围循环,如何继续执行从通道接收下一个值的块?



我正在学习Golang,现在我遇到了这样的情况。假设我有一个整型的通道:ints = make(chan int)一段时间后,我一直在接收值。所以我在我的频道上运行range循环:

for update := range ints {
if update > 10 { // let's say update == 15 for example
// Here I want to continue execution of this block, however having
// the next value of update var, even though it will be <= 10. 
// lets say next value is received and update == 5.
fmt.Println(update) // So this should print "5", not "10"
continue
} else {
fmt.Println("less than 10")
continue
}
}

基本上,我想让这个块休眠一段时间,直到从通道接收到下一个值,然后继续执行,因为更新变量现在有不同的值。

我的第一个想法是创建一个类似于&;isnewvaluerreceived &;bool变量,并使用它在我想要的地方继续执行。然而,这似乎是一个错误的解决方案,因为程序的逻辑可能会变得更加复杂。

请帮我找到解决这个问题的方法。提前感谢!

乌利希期刊指南:

hasGoneAbove := false // initially set to false as no values have been received
hasGoneAbove2 := false
hasGoneAbove3 := false
hasGoneAbove3 := false
for update := range ints {
if hasGoneAbove{
doSomeJob()
hasGoneAbove = false
hasGoneAbove2 = true
continue
}
if hasGoneAbove2{
doSomeJob2()
hasGoneAbove2 = false
hasGoneAbove3 = true
continue
}
if hasGoneAbove3{
doSomeJob3()
hasGoneAbove3 = false
continue
}
if update > 10 { 
hasGoneAbove = true
} else {
fmt.Println("less than 10")
}
}

试着理解你的问题,你似乎想使用一个状态跟踪变量:

hasGoneAbove := false // initially set to false as no values have been received
for update := range ints {
if hasGoneAbove{
fmt.Println(update)
hasGoneAbove = false
}
if update > 10 { 
hasGoneAbove = true
} else {
fmt.Println("less than 10")
}
}

更新:在这种情况下,只保存内存中的最后一个值:

var lastValue int // use zero value
for update := range ints {
if lastValue > 2{
doSomeJob2()
}
if hasGoneAbove > 3{
doSomeJob3()
}
if lastValue > 10{
doSomeJob()
} else {
fmt.Println("less than 10")
}
lastValue = update
}

注意:根据你的问题中的代码,如果LastValue是10,那么所有三个函数都将执行。根据它们的计算密集程度,您可能希望在一个程序中运行它们。

相关内容

最新更新