首頁  >  文章  >  後端開發  >  Go中如何傳遞相容介面的切片?

Go中如何傳遞相容介面的切片?

Mary-Kate Olsen
Mary-Kate Olsen原創
2024-10-25 06:01:02500瀏覽

How to Pass Slices of Compatible Interfaces in Go?

在Go 中傳遞相容介面的切片

在Go 中,將一個介面的切片傳遞給需要一個介面的切片的函數時可能會遇到困難不同的接口,即使前者包含後者。為了說明這個問題,考慮兩個介面 A 和 B,其中 A 包含 B。

`
type A 介面{

Close() error
Read(b []byte) (int, error)

}

type B interface {

Read(b []byte) (int, error)

}
`

}

`

}
return 10, nil
`


}
return nil
`


}

`

`


具體來說,Impl struct 實作了兩個介面:

fmt.Println("in single")
`

type Impl struct {}
func (I Impl) Read(b []byte) (int, error ) {

fmt.Println("in slice")

}

func (I Impl) Close() error {


雖然

}

`

雖然

}

`

雖然單一項目可以毫無問題地跨函數傳遞,但傳遞切片會遇到錯誤:

`

func single(r io.Reader) {
newSlice[i] = v


}
func slice( r []io.Reader) {

}impl := &Impl{}single(impl) / /workslist := [ ]A{impl}slice(list) // 失敗`要解決此問題,您必須建立預期的新切片輸入([]io.Reader) 並用來源切片([ ]A) 中的元素填滿它:`newSlice := make([]io.Reader, len(list))for i, v := range list { }slice(newSlice)`這種方法允許您將一個介面的切片傳遞給函數期待另一個相容介面的切片,解決了嘗試直接傳遞原始切片時引發的錯誤。

以上是Go中如何傳遞相容介面的切片?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn