范围值是整数。

huangapple go评论72阅读模式
英文:

Range value is int

问题

我有一个需要在stopCs上循环发送struct{}{}消息的函数。问题是循环中的stopC是一个int类型。为什么会这样,我该如何修复它?

func myfunc() {
    var stopCs []chan struct{}

    // 将 stopC 添加到 stopCs

    return func() {
        for stopC := range stopCs {
            stopC <- struct{}{}
        }
    }
}

问题出在stopCs的类型定义上,它是一个通道(channel)的切片。在循环中,range stopCs会返回切片中的索引,而不是通道本身。要修复这个问题,你可以将循环中的stopC改为_,表示忽略索引,然后通过stopCs[stopC]来访问通道。修复后的代码如下:

func myfunc() {
    var stopCs []chan struct{}

    // 将 stopC 添加到 stopCs

    return func() {
        for _, stopC := range stopCs {
            stopC <- struct{}{}
        }
    }
}

这样就可以正确地在stopCs上循环发送消息了。

英文:

I have a function that needs to cycle over stopCs sending a struct{}{} message. Problem is the stopC in the range is an int. Why, and how do I fix it?

func myfunc() {
 	var stopCs []chan struct{}

    // Append to stopCs

	return func() {
		for stopC := range stopCs {
			stopC &lt;- struct{}{}
		}
	}

答案1

得分: 2

for ... range语句允许两种类型的赋值,第一种是你使用的方式,它遍历索引;第二种是遍历索引和值。简而言之,你应该使用以下方式:

for i, stopC := range stopCs {

而不是

for i := range stopCs {

引用规范

> 如果最后一个迭代变量是空白标识符,那么range子句等同于没有该标识符的相同子句。

英文:

The for ... range statement allows for two types of assignment, the
first is the one you used which iterates over the indices and the second is
the one that iterates over the indices and the values. In short, you want

for i, stopC := range stopCs {

instead of

for i := range stopCs {

To cite the spec:

> If the last iteration variable is the blank identifier, the range clause is equivalent to the same clause without that identifier.

huangapple
  • 本文由 发表于 2021年5月24日 05:21:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/67664480.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定