Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointer to struct satisfy interface

I scanned the Revel framework's Go code and it seems that pointers satisfy interface requirements. See the snippets below.

type Result interface {
    Apply(req *Request, resp *Response)
}

type RenderTextResult struct {
    text string
}

func (r RenderTextResult) Apply(req *Request, resp *Response) {
    resp.WriteHeader(http.StatusOK, "text/plain; charset=utf-8")
    resp.Out.Write([]byte(r.text))
}

func (c *Controller) RenderText(text string, objs ...interface{}) Result {
    finalText := text
    if len(objs) > 0 {
        finalText = fmt.Sprintf(text, objs...)
    }
    return &RenderTextResult{finalText}
}

What's the reasoning behind this? The framework is returning a struct value instead of a struct pointer for rendering JSON, though:

type RenderJsonResult struct {
    obj      interface{}
    callback string
}

// Uses encoding/xml.Marshal to return XML to the client.
func (c *Controller) RenderXml(o interface{}) Result {
    return RenderXmlResult{o}
}

I can't seem to grasp the subtle (?) differences.

like image 437
Carl Avatar asked May 25 '26 11:05

Carl


1 Answers

Yes, pointers implicitly have all the methods of the type they point to. See the FAQ sections "Why do T and *T have different method sets?" and "Methods on values or pointers?"

like image 195
ChrisH Avatar answered May 28 '26 09:05

ChrisH



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!