【发布时间】:2013-11-02 11:14:34
【问题描述】:
使用 golang html/template(与 text/template 的行为相同)。如果我有一个具有接口类型成员的结构,则我无法访问基础类型的成员(特别是尝试访问实现接口 InnerInterface 但通过 InnerInterface 接口类型返回的结构上的字段,而不是结构类型)。
http://play.golang.org/p/ZH8wSK83oM
package main
import "fmt"
import "os"
import "html/template"
type InnerInterface interface{ InnerSomeMethod() }
type MyInnerStruct struct { Title string }
func (mis MyInnerStruct)InnerSomeMethod() { fmt.Println("Just to show we're satisfying the interface") }
type MyOuterStruct struct { Inner InnerInterface }
func main() {
fmt.Println("Starting")
arg := MyOuterStruct{Inner:MyInnerStruct{Title:"test1"}}
err := template.Must(template.New("testtmpl").Parse("{{.Inner.Title}}")).Execute(os.Stdout, arg)
if err != nil { panic(err) }
}
更改:type MyOuterStruct struct { Inner InnerInterface } 为一个完全通用的接口,即type MyOuterStruct struct { Inner interface{} } 使其正确呈现。这让我相信interface{} 被渲染引擎特别对待。
当我希望能够动态评估这样的字段时,是否有比使用interface{} 更好的方法?
【问题讨论】: