[non-pointer struct].<Method with pointer receiver> cannot be invoked 
directly in a template.

package main

import (
"fmt"
"bytes"
"html/template"
)

type Wrapper struct {
raw []int
}

func (w *Wrapper) IsZero() bool {
if  len(w.raw) == 0{
return true
}
return false
}


var tmplText = `
{{.IsZero}}
` 

var tmpl = template.Must(template.New("test").Parse(tmplText))

func main() { 
wrapped := Wrapper{}
fmt.Println(wrapped.IsZero())

buff := &bytes.Buffer{}
if err := tmpl.Execute(buff, wrapped); err != nil {
panic(err)
}

fmt.Println(buff.String())
}

Will produce: 

panic: template: test:2:3: executing "test" at <.IsZero>: can't evaluate field 
IsZero in type main.Wrapper

goroutine 1 [running]:
main.main()
        /tmp/sandbox009718456/prog.go:33 +0x200



However, changing wrapped from Wrapper to a *Wrapper will work.  

https://play.golang.org/p/lviUVF770c2

Again this might be expected, but I found it a surprised (because I can 
clearly call the method outside the template).  In my real life case, this 
was layers deep in a structs I had to unpack and experiment with to find 
the cause.

The error wasn't clear as to why this was happening, I could not find 
documentation within template to hint at a limitation (maybe I missed it or 
I did not interpret the meaning of something correctly).

What I'm looking from this post:

   - Are my assumptions correct or is the proof above invalid
   - If the proof is valid, is this expected behavior?
   - If expected, is there documentation for this?
   - and, can we see a way to have better error output, I know this is 
   probably difficult due to trying to reflect on what is a field vs a method 
   when something can't be found

Also, trying to document the error here so it gets picked up in Google when 
looking for this error condition, as I was unable to find anything similar.

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/4f28f591-1dfc-45d3-b6ac-707734fad394%40googlegroups.com.

Reply via email to