Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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?

like image 708
Eli Avatar asked Oct 21 '25 02:10

Eli


1 Answers

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
}
like image 151
tux21b Avatar answered Oct 22 '25 16:10

tux21b



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!