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

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

部分嵌入結構

部分嵌入結構

Go
慕桂英4014372 2023-03-15 14:42:08
我可以將類型 A 嵌入到 B 中。type A struct {  R int64  S int64}type B struct {  A}但是我如何只嵌入一個字段呢?type B struct {  A.R // does not work}
查看完整描述

3 回答

?
米琪卡哇伊

TA貢獻1998條經驗 獲得超6個贊

假設您的兩種結構數據類型A和B.


如果你想要A并且B都有一個名為Ftype 的字段T,你可以這樣做


type (

    A struct {

        F T

    }


    B struct {

        F T

    }

)

如果您只想更改T源代碼中一個位置的類型,您可以像這樣抽象它


type (

    T = someType


    A struct {

        F T

    }


    B struct {

        F T

    }

)

F如果您只想更改源代碼中一個位置的名稱,您可以像這樣抽象它


type (

    myField struct {

        F T

    }


    A struct {

        myField

    }


    B struct {

        myField

    }

)

如果您有多個要抽象的可提取字段,則必須像這樣單獨抽象它們


type (

    myField1 struct {

        F1 T1

    }

    myField2 struct {

        F2 T2

    }

    

    A struct {

        myField1

        myField2

    }

    

    B struct {

        myField1

    }

)


查看完整回答
反對 回復 2023-03-15
?
白板的微信

TA貢獻1883條經驗 獲得超3個贊

您不能嵌入單個字段。您只能嵌入整個類型。


如果要嵌入單個字段,則需要創建一個僅包含該字段的新類型,然后嵌入該類型:


type R struct {

  R int64

}


type B struct {

  R

}


查看完整回答
反對 回復 2023-03-15
?
Helenr

TA貢獻1780條經驗 獲得超4個贊

這是我現在最好的解決方案......


type A struct {

  R int64

  S int64

}


type B struct {

  R A

}

然后在實施過程中...


&B{

 R: &A{

   R,

   // S, - ideally we would not be able to pass in `S`

 }

}

我不喜歡這個解決方案,因為我們仍然可以傳入S...


更新:基于@HymnsForDisco 的回答,這可以編碼為...


// A type definition could be used `type AR int64`,

//   instead of a type alias (below), but that would

//   require us to create and pass the `&AR{}` object,

//   to `&A{}` or `&B{}` for the `R` field.

type AR = int64


type A struct {

  R AR

  S int64

}


type B struct {

  R AR

}

并實施為...


&B{

  R,

}


查看完整回答
反對 回復 2023-03-15
  • 3 回答
  • 0 關注
  • 126 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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