糟糕的标题,但我不知道如何在字符限制内描述它。
作为一项学习练习,我正在尝试编写一个模拟彩票抽奖的小围棋程序。它抽取六个随机数作为获胜组,然后不断抽取随机整数的随机数组,直到您再次获得该组。
首先我写了一个函数,它接受一个 channel 并无限循环“将 6 个随机整数的数组添加到 channel ”:
func draw(ch chan<- [6]int) {
generator := rand.New(rand.NewSource(time.Now().UnixNano()))
for {
ch <- [6]int{
generator.Intn(100),
generator.Intn(100),
generator.Intn(100),
generator.Intn(100),
generator.Intn(100),
generator.Intn(100),
}
}
}
然后在main()
我指定两个操作系统线程,创建一个可以容纳 250 个 6 整数数组的 channel ,然后启动我的 draw()
在 goroutine 中运行。
runtime.GOMAXPROCS(2)
ch := make(chan [6]int, 250)
go draw(ch)
接下来,我从 channel 中获取一个获胜的集合(例如 [4 8 15 16 23 42]
),然后是“当前”集合,即最近的平局。我将 game_played 计数器设置为 1:
winning := <- ch
current := <- ch
games_played := 1
这是棘手的一点。
在无限循环中,我检查当前抽奖是否等于中奖抽奖。如果是,我打印玩过的游戏数,并从循环中跳出。
如果不是,我设置current
到新的平局,并增加计数器。然后循环应该运行 if winning == current...
一遍又一遍地检查,直到匹配为止。
for {
if winning == current {
fmt.Println(games_played)
break
} else {
current := <- ch
games_played += 1
}
}
这就是问题所在:倒数第四行,current := <- ch
, 抛出一个编译器错误,'current declared and not used'。我想说“是的,我知道在向下读取之后它不会被使用,但它是在循环内声明的,所以它的值在下一次迭代中很重要。”但是我不知道怎么做,或者我是否做了一些愚蠢的事情。显然,我对 Go 完全一无所知。但对我来说,仔细想想,逻辑是合理的。我是不是搞砸了什么?
(注意:我知道 [1 2 3]
的平局不等于 [2 3 1]
的疏忽,暂时忽略它。)
最佳答案
第二个电流在if
中范围。替换 current := <- ch
与 current = <- ch
(没有冒号)。使用 :=
时你定义了一个新的 current
嵌套范围内的变量。
if winning == current {
fmt.Println(games_played)
break
} else {
current := <- ch
games_played += 1
}
相当于:
if winning == current {
fmt.Println(games_played)
break
} else {
var current int[6] // you don't want this, as it shadows your
// current form the outher scope
current = <- ch // you want only this guy
games_played += 1
}
关于go - “已声明但未使用”是因为 Go 编译器无法考虑循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34995808/