英文:
Resolving an invalid memory address or nil pointer dereference
问题
我正在为你翻译以下内容:
我在这个问题上碰壁了。我无法将HTTP响应分配给一个结构体。
我设置了如下的结构体:
type DataConnect struct {
Response *Response
}
type Response struct {
response []byte
errors []string
}
然后,相关的函数如下所示(为了可读性进行了简化):
func (d *DataConnect) send() bool {
...
out, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println(err)
}
fmt.Printf("%s\n", out) // 这个可以工作
d.Response.response = out // 这个不工作
}
执行上述代码会导致以下错误:
panic: runtime error: invalid memory address or nil pointer dereference
[signal 0xb code=0x1 addr=0x0 pc=0x36532]
goroutine 1 [running]:
github.com/DataConnect.(*DataConnect).send(0xc2000af4a0, 0x232a00)
github.com/DataConnect/DataConnect.go:160 +0xc22
如果我将DataConnect.Response.response
的类型更改为interface{}
,我可以成功保存它,但是我需要它的类型为[]byte
,因为后面我将对内容进行json.Unmarshal
操作。
有人知道为什么这个不起作用吗?
英文:
Banging my head on this one. I can't get an HTTP Response to assign to a struct.
I have my structs set up like so:
type DataConnect struct {
Response *Response
}
type Response struct {
response []byte
errors []string
}
Then the function in question is laid out like so (trimmed for readability):
137 func (d *DataConnect) send() bool {
...
154 out, err := ioutil.ReadAll(resp.Body)
155 if err != nil {
156 fmt.Println(err)
157 }
158
159 fmt.Printf("%s\n", out) // THIS WORKS
160 d.Response.response = out // THIS DOES NOT WORK
161 }
Doing that results in the following error:
panic: runtime error: invalid memory address or nil pointer dereference
[signal 0xb code=0x1 addr=0x0 pc=0x36532]
goroutine 1 [running]:
github.com/DataConnect.(*DataConnect).send(0xc2000af4a0, 0x232a00)
github.com/DataConnect/DataConnect.go:160 +0xc22
Now if I change DataConnect.Response.response
to type interface{}
I can save successfully to it, however I need it in []byte
as later I will be doing a json.Unmarshal on the content.
Does anybody have any idea why this isn't working?
答案1
得分: 2
我怀疑在第160行,d要么是空值,要么d.Response是空值。如果是这样的话,你需要决定是否合适,并在不合适的情况下更改你的代码。
英文:
I suspect either d is nil or d.Response is nil on line 160. If that is true, you need to decide if that is appropriate and change your code if it is not.
答案2
得分: 1
我怀疑@alex是正确的,将你的代码更改为查找nil的内容(从第159行开始):
fmt.Printf("%s\n", out) // 这个是有效的
if d != nil && d.Response != nil {
d.Response.response = out // 这个是无效的
} else {
// 适当的错误记录和处理
}
英文:
I suspect @alex is correct, change your code to something that looks for nil (from line 159):
fmt.Printf("%s\n", out) // THIS WORKS
if d != nil && d.Response != nil {
d.Response.response = out // THIS DOES NOT WORK
} else {
// appropriate error logging and handling
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论