我是golang的新手,我来自php.
我想在结构上定义一个方法来验证http请求.但是我在访问struct字段时遇到了一些问题.
有我的代码.
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)
}
Run Code Online (Sandbox Code Playgroud)
当我运行此代码,然后我得到低于结果
2015/07/21 13:59:50 &{}
2015/07/21 13:59:50 &{ReqAbstract:{} Title:Example Title}
Run Code Online (Sandbox Code Playgroud)
有没有办法在Validate()方法上访问struct字段,如Validate2()方法?
您无法从内部结构访问外部结构字段.只有外部的内场.你可以做的是作曲:
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
}
Run Code Online (Sandbox Code Playgroud)