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

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度