[英]How do I use type switch on struct fields (when field is of interface type)?
[英]How do I use reflect to check if the type of a struct field is interface{}?
我正在使用reflect包來確定struct字段的類型是interface{}
我想像這樣進行比較(其中t
是reflect.Type
):
if t == reflect.TypeOf(interface{}) {
}
問題是編譯器抱怨: type interface {} is not an expression
。
無論如何都要檢查結構字段的類型是否是interface{}
?
您可以通過創建nil實例並使用反射來獲取接口Y
的類型:
yType := reflect.TypeOf((*Y)(nil)).Elem()
然后使用表達式
reflect.TypeOf(x).Implements(yType)
檢查類型是否實現了接口。
接口本身無法實例化。 作為空接口的接口{}接口由所有類型實現,因此所有字段都實現該接口。
https://play.golang.org/p/gRfheIW_9Y
實際上它也適用於空接口{}本身,但這將始終返回true(如果我沒有遺漏某些東西):
interface{}
是一個類型,而reflect.TypeOf()
需要一個值。 所以你不能將文字interface{}
傳遞給它。 您只能傳遞一個值。
回到原來的問題。 讓我們看一個struct
示例:
type My struct {
A int
B interface{}
C io.Reader
}
您想知道字段的類型是否為interface{}
。 獲取struct
類型的reflect.Type
,然后可以使用Type.Field()
或Type.FieldByName()
訪問字段。
這將為您提供一個類型為reflect.StructField
的值,該值存儲字段的類型。
到現在為止還挺好。 但是我們應該將它與什么進行比較? interface{}
是一個包含0個方法的接口類型。 您不能擁有(實例化)該類型的值。 您只能擁有具體類型的值,但是,它們可能包含在接口類型中。
您可以使用Type.Kind
,並將其與reflect.Interface
進行比較,它會告訴您它是否是一個接口,但對於所有接口類型都是true
。 您還可以檢查它是否有0個方法使用Type.NumMethod()
,對於interface{}
必須為0,但其他接口也可以有0個方法...
您可以使用Type.Name
,但由於interface{}
是未命名的類型,因此其名稱為空字符串""
(還有其他未命名的類型)。 您可以使用Type.String()
為空接口返回"interface {}"
:
t := reflect.TypeOf(My{})
for i := 0; i < t.NumField(); i++ {
f := t.Field(i)
fmt.Printf("Field %q, type: %-12v, type name: %-8q, is interface{}: %v\n",
f.Name, f.Type,
f.Type.Name(),
f.Type.String() == "interface {}",
)
}
輸出(在Go Playground上試試):
Field "A", type: int , type name: "int" , is interface{}: false
Field "B", type: interface {}, type name: "" , is interface{}: true
Field "C", type: io.Reader , type name: "Reader", is interface{}: false
您可能會發現此相關問題有趣/有用: 使用反射識別非內置類型
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.