Go 从嵌入式结构访问结构字段

Go 从嵌入式结构访问结构字段,go,Go,我想在结构上定义一个验证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 {

我想在结构上定义一个验证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)
}
当我运行此代码时,我得到以下结果

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
}

你可以用指向他自己的点来定义Field

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}

检查