doutiao2540 2018-02-24 22:15
浏览 37
已采纳

指针离开循环后变为零

Here is a peace of my code:

candles := make([]*base.OHLCVItem, 100)

for i, item := range msgStrSl {
    newCandle, err := parseCandleFromString(item)
    newCandle.Pair = pair
    newCandle.Timeframe = timeframe

    if err != nil {
        bWsLog.WithError(err).Errorf("Failed to parse candle %d.", i)
        continue
    }

    if newCandle == nil {
        panic("nil candle")
    }

    candles = append(candles, newCandle)

    bWsLog.Infof("Sn candle: %d", candles[len(candles)-1].Timestamp)
}

bWsLog.Info(candles[0])
bWsLog.Info(candles[1])
sort.SliceStable(candles, func(i, j int) bool {
    bWsLog.Infof("%d %+v %+v", len(candles), candles[i], candles[j])
    return candles[i].Timestamp < candles[j].Timestamp
}

Logs after the loop say that value is nil. But log inside the loop prints the object (so it is not a nil at that point) I'm new to Go and I can figure out why all the elements in slice became nil after the loop finishes. Could you help me with this issue please?

  • 写回答

1条回答 默认 最新

  • douyun3887 2018-02-24 22:21
    关注

    You create a list of 100 pointers, all are nil, then append to it at position 101. you print the last element, and it's indeed not nil - but it's also not the first one. It's 101, 102, ... and so on. Then you print the first two elements and they are indeed nil. You basically appended a bunch of pointers to a list of 100 nils.

    Just change the first line to:

    candles := make([]*base.OHLCVItem, 0, 100)
    

    Which will create an empty slice, but with a capacity of 100.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本