Variable declared and not used in a for loop

This time came up with a couple of times for Gohere, 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 he gctelling me that I am not using curWeight?

+3
source share
2 answers

Note that the range ( for _, curWeight := range stack) construct copies the elements one by one. This way, you simply copy the value, and then you do not use the copy for further calculations, printing, or returning. You just release the copy.

So, I assume that your initial idea was to add weight to the stack and get it back. 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
}
+5
source

curWeight , , .

Go , , - . , _.

0

All Articles