[英]variable declared and not used in a for loop
This one has come up a couple times for Go
here, but I think my experience is unique.这个已经出现了几次
Go
在这里,但我认为我的经验是独一无二的。 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
?为什么
gc
告诉我我没有使用curWeight
?
Please note that the range construct ( for _, curWeight:= range stack
) does copy the elements, one after another.请注意,范围构造(
for _, curWeight:= range stack
)确实会一个接一个地复制元素。 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 < size; i++ {
stack[i] = Weight{startSpread, rand.Float64(), rand.Float64()}
}
return stack
}
You're assigning to curWeight
twice, but you're not using the value in either place.您分配给
curWeight
两次,但您没有在任何地方使用该值。
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. Go 坚持认为,如果将值分配给变量,则必须在程序中的某个潜在点读回该值。 If you're not going to read it, then assign to
_
instead.如果您不打算阅读它,请改为分配给
_
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.