Why does greets give me invalid memory address or nil pointer dereference
when running?
type Response struct {
Message string `json:"message"`
}
type ResponseList struct {
Items []*Response `json:"items"`
}
func (gs *GreetingService) List(r *http.Request, req *Request, resp *ResponseList) error {
greets := make([]*Response,2,2)
greets[0].Message="hello"
greets[1].Message="goodbye"
resp.Items = greets
return nil
}
You haven't allocated the Response objects, just pointers. Pointers are inited to nil.
You could say greets[0] := &Response{Message: "hello"}
. Or, perhaps better, start with an empty slice and append
as many *Response
s as you want:
greets := []*Response{} // or ResponseList{}
greets = append(greets, &Response{Message: "hello"})
greets = append(greets, &Response{Message: "goodbye"})
Edit: Note Anonymous's alternative: you can use a literal to set up the whole structure if you know the number of Response
s, as in resp.Items = {{Message: "hello"}}
. Works even though Response is a pointer, and works without an explicit type name on each Response
. Very cool.
The support for slice and struct literals in Go can help you avoid the boilerplate as well as get your code right.
Here's how to write your List
method using a slice literal.
func (gs *GreetingService) List(r *http.Request, req *Request, resp *ResponseList) error {
resp.Items = []*Response{
{Message: "hello"},
{Message: "goodbye"},
}
return nil
}