简体   繁体   中英

accessing struct fields from embedded struct

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, I get the 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?

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
}

You can define filed with point to himself

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

This will output:

2009/11/10 23:00:00 &{ReqAbstract:{selfPointer:0x10438180} Title:Example Title} 2009/11/10 23:00:00 &{ReqAbstract:{selfPointer:0x10438180} Title:Example Title}

Check playground

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM