2 回答

TA貢獻1982條經驗 獲得超2個贊
您不能從內部結構訪問外部結構字段。只有來自外部的內部字段。你可以做的是組成:
type CommonThing struct {
A int
B string
}
func (ct CommonThing) Valid() bool {
return ct.A != 0 && ct.B != ""
}
type TheThing struct {
CommonThing
C float64
}
func (tt TheThing) Valid() bool {
return tt.CommonThing.Valid() && tt.C != 0
}

TA貢獻1890條經驗 獲得超9個贊
你可以用指向自己的方式定義歸檔
package main
import (
"log"
)
type ReqAbstract struct{
selfPointer interface{}
}
func (r *ReqAbstract) Assign(i interface{}) {
r.selfPointer = i
}
func (r *ReqAbstract) Validate() error {
log.Printf("%+v", r.selfPointer)
return nil
}
func (r *ReqAbstract) Validate2(req interface{}) error {
log.Printf("%+v", req)
return nil
}
type PostReq struct {
ReqAbstract
Title string
}
func NewPostReq(title string) *PostReq {
pr := &PostReq{Title:title}
pr.Assign(pr)
return pr
}
func main() {
request := NewPostReq("Example Title")
request.Validate()
request.Validate2(request)
}
這將輸出:
2009/11/10 23:00:00 &{ReqAbstract:{selfPointer:0x10438180} Title:Example Title} 2009/11/10 23:00:00 &{ReqAbstract:{selfPointer:0x10438180} Title:Example Title}
檢查操場
- 2 回答
- 0 關注
- 174 瀏覽
添加回答
舉報