亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

從嵌入式結構訪問結構字段

從嵌入式結構訪問結構字段

Go
HUH函數 2021-10-25 16:09:29
我想在結構上定義一個方法來驗證 http 請求。但是我在訪問結構字段時遇到了一些問題。有我的代碼。package mainimport "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() 方法?
查看完整描述

2 回答

?
臨摹微笑

TA貢獻1982條經驗 獲得超2個贊

您不能從內部結構訪問外部結構字段。只有來自外部的內部字段。你可以做的是組成:


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

}


查看完整回答
反對 回復 2021-10-25
?
當年話下

TA貢獻1890條經驗 獲得超9個贊

你可以用指向自己的方式定義歸檔


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)

}

這將輸出:


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


檢查操場


查看完整回答
反對 回復 2021-10-25
  • 2 回答
  • 0 關注
  • 174 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號