dongpo8250 2015-07-21 11:16
浏览 26
已采纳

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

i am new in golang, i am coming from php.

i want to define a method on a struct for validating http request. but i have some problems about accessing struct fields.

there is my code.

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)
}

when i run this code, then i getting below result

2015/07/21 13:59:50 &{}
2015/07/21 13:59:50 &{ReqAbstract:{} Title:Example Title}

is there any way to access struct fields on Validate() method like Validate2() method ?

  • 写回答

2条回答 默认 最新

  • doushuo1080 2015-07-21 11:31
    关注

    You cannot access outer struct fields from inner struct. Only inner fields from the outer. What you can do is composing:

    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
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 雷达辐射源信号参考模型
  • ¥15 html+css+js如何实现这样子的效果?
  • ¥15 STM32单片机自主设计
  • ¥15 如何在node.js中或者java中给wav格式的音频编码成sil格式呢
  • ¥15 不小心不正规的开发公司导致不给我们y码,
  • ¥15 我的代码无法在vc++中运行呀,错误很多
  • ¥50 求一个win系统下运行的可自动抓取arm64架构deb安装包和其依赖包的软件。
  • ¥60 fail to initialize keyboard hotkeys through kernel.0000000000
  • ¥30 ppOCRLabel导出识别结果失败
  • ¥15 Centos7 / PETGEM