首頁  >  文章  >  後端開發  >  如何在 Go 中將一種介面類型的切片轉換為另一種介面類型?

如何在 Go 中將一種介面類型的切片轉換為另一種介面類型?

Susan Sarandon
Susan Sarandon原創
2024-10-26 16:27:02263瀏覽

How to Convert a Slice of One Interface Type to Another in Go?

包含不同介面的切片的型別轉換

在Go中,有可能會遇到需要傳遞一個的切片的場景一個函數的接口,該函數需要不同的相容接口的一部分。考慮以下範例:

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

type B interface {
    Close() error
}

type Impl struct {}

// Implementation of interface A and B
func (I Impl) Close() error {...}
func (I Impl) Read(b []byte) (int, error) {...}</code>

介面相容性

在此範例中,介面 A 包含介面 B,即實作 A 的每個型別也實作 B。結果,A 的具體實現,例如 Impl,同時滿足 A 和 B。

傳遞單一值

如果我們嘗試跨函數傳遞單一項目,它按預期運行:

<code class="go">im := &Impl{}
single(im) // works</code>

傳遞切片

但是,當嘗試傳遞切片時,我們遇到錯誤:

<code class="go">list := []A{t}
slice(list) // FAILS!</code>

錯誤是:cannot use list (type []A) as type []io.Reader in argument to slice

解決方案

要解決此問題,我們可以手動建立所需介面類型的新切片:

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

slice(ioReaders) // now works</code>

以上是如何在 Go 中將一種介面類型的切片轉換為另一種介面類型?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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