从嵌入式结构访问结构字段 [英] accessing struct fields from embedded struct
本文介绍了从嵌入式结构访问结构字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是golang中的新成员,我来自php。
i am new in golang, i am coming from php.
我想在一个结构体上定义一个方法来验证http请求。但我在访问struct字段时遇到了一些问题。
i want to define a method on a struct for validating http request. but i have some problems about accessing struct fields.
有我的代码。
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}
有没有办法访问struct Validate()方法(如Validate2()方法)上的字段?
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
}
这篇关于从嵌入式结构访问结构字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文