3

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?

0

2 Answers 2

9

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
}
Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.