我想將 reflect.Kind 作為 reflect.Interface 的類型,用于實現接口但其實現基于原始類型的類型:type id string對此的替代答案可能是如何獲得在調用 Kind() 時返回 reflect.Interfaces 的任何類型的 reflect.Type。這是Go Playground上的完整示例:type ID interface { myid()}type id stringfunc (id) myid() {}func main() { id := ID(id("test")) fmt.Println(id) fmt.Println(reflect.TypeOf(id)) // How to get the kind to return "reflect.Interface" from the var "id"? fmt.Println(reflect.TypeOf(id).Kind())}
1 回答

慕的地6264312
TA貢獻1817條經驗 獲得超6個贊
reflect.TypeOf()(and reflect.ValueOf()) 期望interface{}. 基本上,無論您傳遞給什么值reflect.TypeOf(),如果它還不是接口值,它將被interface{}隱式包裝。如果傳遞的值已經是接口值,則存儲在其中的具體值將作為interface{}.
為了避免這種“重新打包”,這是指向接口的指針有意義的極少數情況之一,實際上你不能在這里避免它。您必須傳遞一個指向接口值的指針。
因此,如果您將指針傳遞給接口,則該指針將被包裝在一個interface{}值中。您可以使用Type.Elem()獲取“指向類型”的類型描述符:即指針類型的元素類型,這將是您要查找的接口類型的類型描述符。
例子:
id := ID(id("test"))
fmt.Println(id)
t := reflect.TypeOf(&id).Elem()
fmt.Println(t)
fmt.Println(t.Kind())
哪些輸出(在Go Playground上嘗試):
test
main.ID
interface
- 1 回答
- 0 關注
- 139 瀏覽
添加回答
舉報
0/150
提交
取消