dsbckxk165039 2011-06-09 03:27
浏览 107
已采纳

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

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条回答

  • dqby43944 2011-06-09 05:54
    关注

    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
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿