第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

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

如何使用 interface{} 作為通配符類型?

如何使用 interface{} 作為通配符類型?

Go
萬千封印 2021-10-25 17:19:09
該場景是傳遞具有公共字段的類似結(jié)構(gòu),并將它們設(shè)置為作為參數(shù)傳遞的值:package maintype A struct {    Status int}type B struct {    id     string    Status int}// It's okay to pass by value because content is only used inside thisfunc foo(v interface{}, status int) {    switch t := v.(type) {    case A, B:        t.Status = status // ERROR :-(    }}func main() {    a := A{}    foo(a, 0)    b := B{}    b.id = "x"    foo(b, 1)}令我沮喪的是,我收到此錯誤:?  test  go run test.go# command-line-arguments./test.go:15: t.Status undefined (type interface {} has no field or method Status)如果類型轉(zhuǎn)換將 interface{} 轉(zhuǎn)換為底層類型,我做錯了什么?
查看完整描述

1 回答

?
GCT1015

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

}


查看完整回答
反對 回復(fù) 2021-10-25
  • 1 回答
  • 0 關(guān)注
  • 243 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號