在for循环中声明了变量但未使用

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

variable declared and not used in a for loop

问题

这个问题在这里已经出现了几次,但我认为我的经验是独特的。以下是我的代码。

type Stack []Weight

func newStack( size int, startSpread Spread ) Stack {
  stack := make(Stack, size)

  for _, curWeight := range stack {
    curWeight = Weight{ startSpread, rand.Float64( ), rand.Float64( ) }
  }

  return stack
}

为什么gc告诉我我没有使用curWeight

英文:

This one has come up a couple times for Go here, but I think my experience is unique. Here are my codes.

type Stack []Weight

func newStack( size int, startSpread Spread ) Stack {
  stack := make(Stack, size)

  for _, curWeight := range stack {
    curWeight = Weight{ startSpread, rand.Float64( ), rand.Float64( ) }
  }

  return stack
}

Why is gc telling me I'm not using curWeight?

答案1

得分: 5

请注意,range构造(for _, curWeight := range stack)会逐个复制元素。所以,你只是复制了一个值,然后没有将复制用于任何进一步的计算、打印或返回。你只是再次丢弃了复制品。

所以我猜你最初的想法是将权重添加到堆栈并返回它。让我们这样做:

func newStack(size int, startSpread Spread) Stack {
	stack := make(Stack, size)

	for i := 0; i < size; i++ {
		stack[i] = Weight{startSpread, rand.Float64(), rand.Float64()}
	}

	return stack
}
英文:

Please note that the range construct (for _, curWeight := range stack) does copy the elements, one after another. So, you are just copying a value, and then you do not use the copy for any further computations, printing or returning. You just drop the copy again.

So I guess your initial idea was to add the weight to the stack and return it. Let`s do that:

func newStack(size int, startSpread Spread) Stack {
	stack := make(Stack, size)

	for i := 0; i &lt; size; i++ {
		stack[i] = Weight{startSpread, rand.Float64(), rand.Float64()}
	}

	return stack
}

答案2

得分: 1

你在两个地方都给curWeight赋值了,但是你在任何一个地方都没有使用这个值。

Go语言要求如果你给一个变量赋值,那么你必须在程序的某个潜在点读取这个值。如果你不打算读取它,那么可以赋值给_

英文:

You're assigning to curWeight twice, but you're not using the value in either place.

Go insists that if you assign a value to a variable, then you have to read that value back at some potential point in your program. If you're not going to read it, then assign to _ instead.

huangapple
  • 本文由 发表于 2011年6月9日 11:27:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/6287806.html
匿名

发表评论

匿名网友

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

确定