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

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

如何修改未知類型的結構中的字段?

如何修改未知類型的結構中的字段?

Go
神不在的星期二 2023-04-04 17:25:26
我有多個具有一個公共字段的結構;讓我們common在這里稱呼它type Struct1 struct {    foo string    bar string    common string}type Struct2 struct {    baz int    qux string    common string}我想創建一個將 anInterface作為輸入并使 無效的函數common。編譯時不知道可用的結構類型,因此我無法為每種類型創建單獨的函數,也無法使用 switch 語句。PS:在我的用例中,我想取消,common因為它保存了每個結構的創建時間,我想跟蹤結構的歷史,所以我會知道它是否發生變化。將創建時間放在結構中會搞砸,因為每次生成新結構時創建時間都會不同,即使其實際數據可能相同。
查看完整描述

1 回答

?
侃侃爾雅

TA貢獻1801條經驗 獲得超16個贊

定義一個具有公共字段的結構,并使其實現一個接口,該接口表明它能夠使公共字段無效。然后將此結構嵌入到應該能夠使字段無效的其他結構類型中。


// CommonNullifier is able to nullify its common field(s)

type CommonNullifier interface {

? ? ? ? NullifyCommon()

}


// StructCommon contains the common struct fields

type StructCommon struct {

? ? ? ? Common string

}


func (sc *StructCommon) NullifyCommon() {

? ? ? ? sc.Common = ""

}


// Struct1 embeds common fields, thus implements CommonNullifier

type Struct1 struct {

? ? ? ? StructCommon

? ? ? ? Foo string

}


// Struct2 also embeds common fields, thus also implements CommonNullifier

type Struct2 struct {

? ? ? ? StructCommon

? ? ? ? Bar string

}


// NullifyCommon nullfies the 'common' fields in the argument

func NullifyCommon(s CommonNullifier) {

? ? ? ? s.NullifyCommon()

}


您也可以使用反射,但使用接口通常更具可讀性。


查看完整回答
反對 回復 2023-04-04
  • 1 回答
  • 0 關注
  • 137 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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