dpba63888 2018-12-21 14:30
浏览 24
已采纳

从3个单独的切片创建新的组合结构切片时索引超出范围(每个struct属性一个切片)

I have a struct like this:

type Headers struct {
    header            string
    valueFromCalculation    string
    value            float64
}

I need have three slices with the values for each of these:

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%]

Now I want to create a new slice of Headers by combining these. There is one issue, that I believe i'm solving - the length of the valueFromCalcuation is 1 less than the rest of the slices

To create the new slice I want to do this:

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)
}

It is throwing the below error:

"panic: runtime error: index out of range"

How can this be?

I'm accounting for the issue of the index with the valueFromCalculation length being one less than the other struct properties

Here you can see output from before I want to start my loop:

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

Please can someone help me here? I can't see what i'm doing wrong

I'm accounting for the length of the 3rd property being 1 less than the rest

  • 写回答

1条回答 默认 最新

  • dongyuan9292 2018-12-21 14:51
    关注

    It appears you are looping one index too long on headerLabels.

    Try changing i <= len(headerLabels) to i < len(headerLabels)

    And

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

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

报告相同问题?

悬赏问题

  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法