访问嵌套结构值时出现索引超出范围错误。

huangapple go评论66阅读模式
英文:

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

huangapple
  • 本文由 发表于 2014年9月24日 17:31:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/26013400.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定