gpt4 book ai didi

for-loop - 从 3 个单独的 slice (每个结构属性一个 slice )创建新的组合结构 slice 时索引超出范围

转载 作者:数据小太阳 更新时间:2023-10-29 03:32:27 30 4
gpt4 key购买 nike

我有一个这样的结构:

type Headers struct {
header string
valueFromCalculation string
value float64
}

我需要三个 slice ,每个 slice 都有值:

var headerLabels []string
var values []float64
var valueFromCalculation []string


[January February March April May June July August September TOTAL]
[175 167 148 142 125 114 130 120 30 1151]
[15% 15% 13% 12% 11% 10% 11% 10% 3%]

现在我想通过组合这些来创建一个新的 Headers 片段。有一个问题,我相信我正在解决 - valueFromCalcuation 的长度比其余 slice 少 1

要创建新 slice ,我想这样做:

sliceOfHeaders := []*Headers{}

for i := 0; i <= len(headerLabels); i++ {

headerEntry := new(Headers)

headerEntry.header = headerLabels[i]
headerEntry.value = values[i]

if i == len(headerLabels) {
headerEntry.valueFromCalculation = ""
} else {
headerEntry.valueFromCalculation = valueFromCalculation[i]
}

sliceOfHeaders = append(sliceOfHeaders, headerEntry)
}

它抛出以下错误:

“ panic :运行时错误:索引超出范围”

这怎么可能?

我正在考虑 valueFromCalculation 长度比其他结构属性少一的索引问题

在这里你可以看到我想开始循环之前的输出:

header --> [January February March April May June July August September TOTAL]
value --> [175 167 148 142 125 114 130 120 30 1151]
valueFromCalculation --> [15% 15% 13% 12% 11% 10% 11% 10% 3%]
header length --> 10
value length --> 10
valueFromCalculation length --> 9

有人可以帮我吗?我看不出我做错了什么

我考虑的是第三个属性的长度比其余属性少 1

最佳答案

看来您在 headerLabels 上循环一个索引的时间太长了。

尝试改变 i <= len(headerLabels)i < len(headerLabels)

if i == len(headerLabels)if i == len(headerLabels) - 1

关于for-loop - 从 3 个单独的 slice (每个结构属性一个 slice )创建新的组合结构 slice 时索引超出范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53886458/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com