Playground link: http://play.golang.org/p/Ebf5AuJlcP
type Foo interface {}
type Bar interface {
ThisIsABar()
}
// Person implements both Foo and Bar
type Person struct {
Name string
}
func (p Person) ThisIsABar() {}
type FooContext struct {
Something Foo
}
type BarContext struct {
Something Bar
}
func main() {
t := template.Must(template.New("test").Parse("{{ .Something.Name }}\n"))
// This works fine.
if err := t.Execute(os.Stdout, FooContext{Person{"Timmy"}}); err != nil {
fmt.Printf("Error: %s\n", err)
}
// With BarContext, containing the exact same Person but wrapped in a
// different interface, it errors out.
if err := t.Execute(os.Stdout, BarContext{Person{"Timmy"}}); err != nil {
fmt.Printf("Error: %s\n", err)
}
}
When I render a template (via the text/template
package) containing {{ .Something.Name }}
, I can go through interface Foo
which contains no methods, and it works fine. But if I go through interface Bar
instead, I get:
executing "test" at <.Something.Name>: can't evaluate field Name in type main.Bar
Why does the presence of an unrelated method on the interface, that isn't even used, affect the rendering of the template?