How to golan check nil variable

my code is like this when I use req, _ := http.NewRequest("GET", "http://www.github.com", content) , it throws an exception:

 panic: runtime error: invalid memory address or nil pointer dereference [signal 0xb code=0xffffffff addr=0x0 pc=0xaab78] goroutine 1 [running]: net/http.NewRequest(0x34f3b8, 0x3, 0x378020, 0x15, 0xfeec4350, 0x0, 0x10738801, 0x0, 0x0, 0x107000e0) /usr/local/go/src/net/http/request.go:570 +0x498 main.main() /tmp/sandbox056954284/main.go:17 +0xe0 

but when I use req, _ := http.NewRequest("GET", "http://www.github.com", nil) , it works, why? how to set the third argument value

 package main import ( "bytes" "net/http" ) func main() { client := &http.Client{} var content *bytes.Reader content = nil req, _ := http.NewRequest("GET", "http://www.github.com", content) resp, _ := client.Do(req) defer resp.Body.Close() } 
+5
source share
2 answers

The go interface consists of type and value. An interface is only zero if both the type and the value are zero. You provided a type, but not a value: Therefore, NewRequest tried to call Read on an nil struct (interface value).

+4
source
Default content

equals zero, no need to assign it

also you ignore the error returned from NewRequest, do not do this. It tells you why it cannot generate a request.

Normal error handling will look something like this:

 req, err := http.NewRequest("GET", "http://www.github.com", content) if err != nil { // log or complain... req is nil here } else { // do something with req } 

all that is said, if you really just want to know if req is null, do:

 if req == nil { // handle nil req } else { // use req } 

but as mentioned earlier, it's much better to deal with the error. if err not nil, then you basically cannot trust req to be anything valid.

+1
source

Source: https://habr.com/ru/post/1234838/


All Articles