go - 从嵌入式结构访问结构字段

标签 go

我想在结构上定义一个方法来验证 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/

相关文章:

go - 如何获取接口(interface)的reflect.Type?

go - echo web框架绑定(bind)FormFile

戈朗 : Automatic Refresh of a HTTP Page

python - golang <--> python 通信的最简单的 pub-sub 通信,可能跨机器?

go - 安装 Golang Oracle 但得到 "error: undefined reference to ' golang.org_x_tools_container_intsets.popcount'”

go - golang中使用bufio.Scanner时如何继续执行程序

go - Golang以指定的精度将float编码为JSON

go - 为什么 append() 修改提供的 slice ? (见例子)

types - 命名和未命名类型

go - golang中的深度复制数据结构