[英]In Go, Given an interface{} in which I know what interface it implements, how can I convert to it
我當前的問題是我正在實現數據結構,並且已經為它們編寫了迭代器。 我的數據結構,迭代器和所有其他必需的對象都有可見的接口。 在后面,我有一些具體的實現,希望對最終用戶隱藏。
這需要我的許多函數返回interface {}對象,以便我可以存儲任何類型的對象(並將驗證留給最終用戶使用)。
我有一個問題是我遍歷了一個圖。 用於圖形實現的iterator {}返回具體的頂點類型,但是Iterator接口返回interface {}。 由於最終用戶只能使用我的基本Vertex接口,因此我必須嘗試轉換為Vertex接口,以便他們可以使用它。
這是我目前可以想到的最小示例,它說明了我的問題:
package main
import (
"fmt"
"strconv"
)
type Base interface {
Required() string
}
type Concrete struct {
_data int
}
func (con *Concrete) Required() string {
return strconv.Itoa(con._data)
}
func convert(val interface{}) *Base {
if con,ok := val.(*Base); ok {
return con
}
return nil
}
func main() {
conc := new(Concrete)
conc._data = 5
base := convert(conc)
fmt.Println(base)
}
在上面的代碼中,我真的希望convert將類型轉換為* Base。 函數convert將返回值nil而不是我希望的可愛值。
編輯:刪除了未使用的代碼,我以為我已經刪除了它,但我想沒有。
現在,我已經寫完了很長的解釋,我有了一個主意並想出了解決方案:
func convert(val interface{}) Base {
if con,ok := val.(Base); ok {
return con
}
return nil
}
不要嘗試轉換為指針,而只能轉換為Base接口。
我不知道為什么會這樣。 當我在reflect.TypeOf(val)內部進行轉換時,它給出了輸出
*main.Concrete
我希望其他人覺得這有用,並且希望其他人可以回答此答案的“ 為什么”部分。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.