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.

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

报告相同问题?