loops - 离开循环后指针变为 nil

标签 loops pointers go null slice

这是我的代码的和平:

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
}

循环后的日志显示值为 nil。 但是循环内的日志会打印对象(因此此时它不是零) 我是 Go 的新手,我可以弄清楚为什么 slice 中的所有元素在循环结束后都变成了 nil 。 你能帮我解决这个问题吗?

最佳答案

您创建了一个包含 100 个指针的列表,所有指针均为 nil,然后将其附加到位置 101。你打印最后一个元素,它确实不是 nil - 但它也不是第一个。是 101、102……等等。然后你打印前两个元素,它们确实为零。您基本上将一堆指针附加到 100 个 nils 的列表。

只需将第一行更改为:

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

这将创建一个空 slice ,但容量为 100。

关于loops - 离开循环后指针变为 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48968177/

相关文章:

go - 找不到导入 : "google.golang.org/cloud/storage"

go - 这个类型声明是什么意思?

oracle - 遍历Oracle PL/SQL中的表

ios - 意外的迭代性能下降

c - int 指针指向两个结构体指针?

go - 奇怪的 404 服务器错误 (ListenAndServeTLS)

循环中的 Java 扫描器仅获取第一个输入

php - 从数据库自引用表创建嵌套数组并显示在 Smarty 模板的嵌套列表中

c - 将数组/指针传递给c中的结构

c++ - 指向节点的指针不更新节点属性