变量已声明且未在for循环中使用

在这里, Go </ code>出现了几次,但我认为我的经验 是独特的。 这是我的代码。</ p>

 类型Stack [] Weight 

func newStack(size int,startSpread Spread)Stack {
stack:= make(Stack,size)\ n_n表示_,curWeight:=范围堆栈{
curWeight = Weight {startSpread,rand.Float64(),rand.Float64()}
}

返回堆栈
}
</ code> </ pre>

为什么 gc </ code>告诉我我没有使用 curWeight </ code>?</ p>
</ div>

展开原文

原文

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?

2个回答

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
}
dpgui8229808
dpgui8229808 同样,for语句可能适用于i:=范围栈{...}
9 年多之前 回复



您两次分配给 curWeight </ code>,但是您没有使用</ strong> </ p>

Go坚持认为,如果将值分配给变量,则必须在程序的某个潜在位置重新读取该值。 如果您不打算阅读,请改为分配 _ </ code>。</ p>
</ div>

展开原文

原文

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.

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐