gpt4 book ai didi

go - 访问嵌入式结构值时出现索引超出范围错误

转载 作者:IT王子 更新时间:2023-10-29 02:34:23 25 4
gpt4 key购买 nike

当我运行这段代码时出现了超出范围的错误:

开始:

type Ping struct {
Content []aContent
}

type aContent struct {
Type string
Id string
Created_at int64
}

var p Ping

func main() {

f := Ping{Content: []aContent{{Type: "Hello", Id: "asdf"}}}
fmt.Println(f)
fmt.Println(p.Content[0].Created_at) //what's wrong?
}

怎么了?代码可以在这里找到:http://play.golang.org/p/uZm5LaUuGW

最佳答案

Ping 类型的

变量 p 及其字段/属性 Content 未初始化,因此当您访问 的内容时>Content 是一个 slice,它会抛出该错误。为什么?因为未初始化的 slice 的值为 nil。即 p.Content == []

关于go - 访问嵌入式结构值时出现索引超出范围错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26013400/

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