dtziv24262 2014-09-24 01:31
浏览 40
已采纳

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

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条回答 默认 最新

  • douwei1944 2014-09-24 01:41
    关注

    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 == []

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

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部