1 回答

TA貢獻1772條經(jīng)驗 獲得超6個贊
執(zhí)行模板不強制任何參數(shù),Template.Execute()接受類型的值interface{}。
您是創(chuàng)建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實現(xiàn)它的示例:
type HomePage struct {
BasePage
// other home page fields...
}
func (h *HomePage) GetBasePage() BasePage {
return h.BasePage
}
現(xiàn)在顯然只有具有GetBasePage()方法的頁面才能作為值傳遞HasBasePage:
var page HasBasePage = &HomePage{} // Valid, HomePage implements HasBasePage
如果你不想使用接口,你可以使用reflect包來檢查一個值是否是一個結構值,以及它是否嵌入了另一個接口。嵌入的結構出現(xiàn)并且可以像普通字段一樣訪問,例如 with 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:}
- 1 回答
- 0 關注
- 223 瀏覽
添加回答
舉報