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 关注
- 157 浏览
添加回答
举报