我想知道如何构造此示例代码,以帮助避免空指针解除引用恐慌:package mainimport "fmt"type Astruct struct { Number int Letter string}type Bstruct struct { foo int AStructList *[]Astruct}type Cstruct struct { Bstruct}func (a *Astruct) String() string { return fmt.Sprintf("Number = %d, Letter = %s", a.Number, a.Letter)}func main() { astructlist := make([]Astruct, 3) // line 1 for i := range astructlist { // line 2 astructlist[i] = Astruct{i, "a"} // line 3 } // line 4 c := new(Cstruct) c.Bstruct = Bstruct{100, &astructlist} // line 6 for _, x := range(*c.Bstruct.AStructList) { fmt.Printf("%s\n", &x) }}如果省略main()的第1-4和6行,则会出现空指针取消引用恐慌。如果不检查c!= nil,是否有避免这些恐慌的方法?在此先感谢您的帮助!
1 回答
- 1 回答
- 0 关注
- 245 浏览
添加回答
举报
0/150
提交
取消