游乐场链接: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)
}
}
当我渲染一个包含 的模板(通过text/template
包){{ .Something.Name }}
时,我可以通过Foo
不包含任何方法的接口,它工作正常。但是,如果我Bar
改为通过界面,我会得到:
executing "test" at <.Something.Name>: can't evaluate field Name in type main.Bar
为什么界面上存在甚至没有使用的不相关方法会影响模板的呈现?