我想知道如何构造此示例代码以帮助避免空指针解除引用恐慌:
package main
import "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)
}
}
Run Code Online (Sandbox Code Playgroud)
如果省略main()的第1-4行和第6行,我会得到一个空指针解除引用恐慌.如果没有检查c!= nil,有没有办法避免这些恐慌?
在此先感谢您的帮助!
在这种特殊情况下,您可以使用惯用Go.更改AStructList *[]Astruct到AStructList []*Astruct.例如,
package main
import "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)
}
}
Run Code Online (Sandbox Code Playgroud)
通常,您有责任在使用之前nil为指针或测试分配非值nil.当你在没有明确初始化的情况下分配内存时,它被设置为类型的零值,这是nil指针的值.
当分配内存来存储值时,无论是通过声明还是调用make或new,并且没有提供显式初始化,内存都会被赋予默认初始化.这种值的每个元素都设置为其类型的零值:布尔值为false,整数为0,浮点数为0.0,字符串为"",指针,函数,接口,切片,通道和映射为nil.这种初始化是递归完成的,因此,例如,如果没有指定值,则结构数组的每个元素都将其字段归零.
| 归档时间: |
|
| 查看次数: |
4545 次 |
| 最近记录: |