gpt4 book ai didi

go - 如何避免 "invalid memory address or null pointer dereference"错误?

转载 作者:IT王子 更新时间:2023-10-29 01:25:32 24 4
gpt4 key购买 nike

我想知道如何构造此示例代码以帮助避免空指针取消引用 panic :

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)
}
}

如果我省略 main() 的第 1-4 行和第 6 行,我会得到空指针取消引用 panic 。如果不检查 c != nil,有没有办法避免这些 panic ?

在此先感谢您的帮助!

最佳答案

在这种特殊情况下,您可以使用惯用的 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)
}
}

通常,您有责任将非 nil 值分配给指针或在使用前测试 nil。当您分配内存而不显式初始化它时,它被设置为类型的零值,对于指针是 nil

The zero value

When memory is allocated to store a value, either through a declaration or a call of make or new, and no explicit initialization is provided, the memory is given a default initialization. Each element of such a value is set to the zero value for its type: false for booleans, 0 for integers, 0.0 for floats, "" for strings, and nil for pointers, functions, interfaces, slices, channels, and maps. This initialization is done recursively, so for instance each element of an array of structs will have its fields zeroed if no value is specified.

关于go - 如何避免 "invalid memory address or null pointer dereference"错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9464516/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com