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
}
)

TA貢獻1883條經驗 獲得超3個贊
您不能嵌入單個字段。您只能嵌入整個類型。
如果要嵌入單個字段,則需要創建一個僅包含該字段的新類型,然后嵌入該類型:
type R struct {
R int64
}
type B struct {
R
}

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,
}
- 3 回答
- 0 關注
- 126 瀏覽
添加回答
舉報