英文:
Index out of range error when accessing embedded struct value
问题
当我运行这段代码时,我遇到了一个超出范围的错误:
Go:
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) //有什么问题?
}
有什么问题?代码可以在这里找到:http://play.golang.org/p/uZm5LaUuGW
英文:
I get an out of range error when I run this code:
Go:
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?
}
What's wrong? The code can be found here: http://play.golang.org/p/uZm5LaUuGW
答案1
得分: 3
变量 p
的类型是 Ping
,它的字段/属性 Content
没有初始化,所以当你访问 Content
的内容时,它会抛出错误。为什么呢?因为未初始化的 slice
的值是 nil
,即 p.Content == []
。
英文:
variable p
of type Ping
and its field/property Content
is un-initialized, so when you access the content of the Content
which is a slice
, it throws you that error. Why? Because the value of an uninitialized slice
is nil
. i.e p.Content == []
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论