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
?
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 < 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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.