从嵌入式结构访问结构字段
时间:2023-04-12
浏览:403
作者:佚名
积累知识,胜过积蓄金银!毕竟在##column_title##开发的过程中,会遇到各种各样的问题,往往都是一些细节知识点还没有掌握好而导致的,因此基础知识点的积累是很重要的。下面本文《从嵌入式结构访问结构字段》,就带大家讲解一下golang知识点,若是你对本文感兴趣,或者是想搞懂其中某个知识点,就请你继续往下看吧~
问题内容
我想在结构上定义一个方法来验证 http 请求。但我在访问结构字段时遇到了一些问题。
有我的代码。
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)
}
当我运行此代码时,我得到以下结果
2015/07/21 13:59:50 &{}
2015/07/21 13:59:50 &{ReqAbstract:{} Title:Example Title}
有什么方法可以访问 Validate() 方法上的结构字段,如 Validate2() 方法?
正确答案
您不能从内部结构访问外部结构字段。只有外部的内部字段。您可以做的是编写:
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
}
今天关于《从嵌入式结构访问结构字段》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于golang的内容请关注golang学习网公众号!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.20
11.20
11.20
11.20
热门专题
