首頁 > 後端開發 > Golang > 主體

如何將一個介面的切片傳遞給需要 Go 中不同的相容介面切片的函數?

Susan Sarandon
發布: 2024-10-24 20:53:17
原創
457 人瀏覽過

How to Pass a Slice of One Interface to a Function Expecting a Slice of a Different, Compatible Interface in Go?

將介面切片傳遞給Go 中不同的相容介面

在Go 中使用介面時,您可能會遇到需要的情況將一個介面的切片傳遞給需要不同介面切片的函數,儘管第一個介麵包括第二個介面。

考慮以下範例:

<code class="go">type A interface {
    Close() error
    Read(b []byte) (int, error)
}

type Impl struct {}
func (I Impl) Read(b []byte) (int, error) {
    fmt.Println("In read!")
    return 10, nil
}
func (I Impl) Close() error {
    fmt.Println("I am here!")
    return nil
}

func single(r io.Reader) {
    fmt.Println("in single")
}

func slice(r []io.Reader) {
    fmt.Println("in slice")
}

im := &Impl{}
single(im) // works
list := []A{im}
slice(list) // fails: cannot use list (type []A) as type []io.Reader</code>
登入後複製

在傳遞將A 類型的單項傳遞給具有介面參數io.Reader 的函數single 會成功,嘗試將A 的切片傳遞給需要io.Reader 切片的函數切片會失敗。

解:

不幸的是,這個問題是 Go 中的限制。要解決此問題,您必須建立所需介面類型的新切片,並使用現有切片中的元素填充它。

<code class="go">newList := make([]io.Reader, len(list))
for i, elem := range list {
    newList[i] = elem
}

slice(newList) // now works</code>
登入後複製

以上是如何將一個介面的切片傳遞給需要 Go 中不同的相容介面切片的函數?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!