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