html/template: Unable to execute a method on non-pointer struct where method receiver is a pointer (can't evaluate field error)

42 views
Skip to first unread message

John

unread,
Jan 30, 2020, 4:22:53 PM1/30/20
to golang-nuts
[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.  


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.

Reply all
Reply to author
Forward
0 new messages