我想在结构上定义一个方法来验证 http 请求。但我在访问结构字段方面遇到了一些问题。
这是我的代码。
package main
import "log"
type ReqAbstract struct{}
func (r *ReqAbstract) Validate() error {
log.Printf("%+v", r)
return nil
}
func (r *ReqAbstract) Validate2(req interface{}) error {
log.Printf("%+v", req)
return nil
}
type NewPostReq struct {
ReqAbstract
Title string
}
func main() {
request := &NewPostReq{Title: "Example Title"}
request.Validate()
request.Validate2(request)
}
当我运行这段代码时,我得到以下结果
2015/07/21 13:59:50 &{}
2015/07/21 13:59:50 &{ReqAbstract:{} Title:Example Title}
有没有什么方法可以像 Validate2() 方法一样访问 Validate() 方法上的结构字段?
最佳答案
您不能从内部结构访问外部结构字段。只有来自外部的内部字段。您可以做的是编写:
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
}
关于go - 从嵌入式结构访问结构字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31537549/