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