1 回答

TA貢獻1827條經(jīng)驗 獲得超4個贊
盡管 A 和 B 都有一個狀態(tài)字段,但它們不能與類型系統(tǒng)互換。您必須為每個案例設(shè)置單獨的案例。
case A:
t.Status = status
case B:
t.Status = status
}
或者,您可以使用實際接口:
type HasStatus interface {
SetStatus(int)
}
type A struct {
Status int
}
func (a *A) SetStatus(s int) { a.Status = s }
func foo(v HasStatus, status int) {
v.SetStatus(status)
}
如果您有多種類型都具有一組公共字段,您可能需要使用嵌入式結(jié)構(gòu):
type HasStatus interface {
SetStatus(int)
}
type StatusHolder struct {
Status int
}
func (sh *StatusHolder) SetStatus(s int) { sh.Status = s }
type A struct {
StatusHolder
}
type B struct {
id string
StatusHolder
}
- 1 回答
- 0 關(guān)注
- 243 瀏覽
添加回答
舉報