执行模板不会对参数强制执行任何操作,Template.Execute() 接受 interface{} 类型的值。
您是创建HomePage、RegisterPage 和ContactPage 结构的人。是什么阻止您嵌入带有必填字段的 BasePage 结构?你担心你会忘记它吗?您会在第一次测试时注意到它,我不会担心:
type BasePage struct {
Title string
Other string
// other required fields...
}
type HomePage struct {
BasePage
// other home page fields...
}
type RegisterPage struct {
BasePage
// other register page fields...
}
如果你想从代码中检查页面结构是否嵌入了BasePage,我推荐另一种方式:接口。
type HasBasePage interface {
GetBasePage() BasePage
}
实现它的示例HomePage:
type HomePage struct {
BasePage
// other home page fields...
}
func (h *HomePage) GetBasePage() BasePage {
return h.BasePage
}
现在显然只有具有GetBasePage() 方法的页面可以作为HasBasePage 的值传递:
var page HasBasePage = &HomePage{} // Valid, HomePage implements HasBasePage
如果你不想使用接口,你可以使用reflect包来检查一个值是否是一个结构值,以及它是否嵌入了另一个接口。嵌入式结构出现并且可以像普通字段一样访问,例如使用Value.FieldByName(),类型名称为字段名称。
使用reflect检查值是否嵌入BasePage的示例代码:
page := &HomePage{BasePage: BasePage{Title: "Home page"}}
v := reflect.ValueOf(page)
if v.Kind() == reflect.Ptr {
v = v.Elem()
}
if v.Kind() != reflect.Struct {
fmt.Println("Error: not struct!")
return
}
bptype := reflect.TypeOf(BasePage{})
bp := v.FieldByName(bptype.Name()) // "BasePage"
if !bp.IsValid() || bp.Type() != bptype {
fmt.Println("Error: struct does not embed BasePage!")
return
}
fmt.Printf("%+v", bp)
输出(在 Go Playground 上试试):
{Title:Home page Other:}