猿问

如何判断我的 interface{} 是否是一个指针?

如果我有一个接口被传递给一个函数,有没有办法判断传入的项目是一个结构体还是一个指向结构体的指针?我写了这个愚蠢的测试来说明我需要弄清楚什么。


type MyStruct struct {

    Value string

}


func TestInterfaceIsOrIsntPointer(t *testing.T) {

    var myStruct interface{} = MyStruct{Value: "hello1"}

    var myPointerToStruct interface{} = &MyStruct{Value: "hello1"}

    // the IsPointer method doesn't exist on interface, but I need something like this

    if myStruct.IsPointer() || !myPointerToStruct.IsPointer() { 

        t.Fatal("expected myStruct to not be pointer and myPointerToStruct to be a pointer")

    }

}


德玛西亚99
浏览 383回答 3
3回答

月关宝盒

func isStruct(i interface{}) bool {    return reflect.ValueOf(i).Type().Kind() == reflect.Struct}您可以根据需要通过更改类型进行测试,例如reflect.Ptr. reflect.Indirect(reflect.ValueOf(i))在确保它是一个指针之后,您甚至可以获取指向值。添加:好像reflect.Value有Kind方法所以reflect.ValueOf(i).Kind()就够了。

慕斯王

您可以使用反射包:i := 42j := &ikindOfJ := reflect.ValueOf(j).Kind()fmt.Print(kindOfJ == reflect.Ptr)

湖上湖

如果您知道接口的“真实”类型,则可以简单地使用type switch:type MyStruct struct {    Value string}func TestInterfaceIsOrIsntPointer(t *testing.T) {    var myStruct interface{} = MyStruct{Value: "hello1"}    var myPointerToStruct interface{} = &MyStruct{Value: "hello1"}    // the IsPointer method doesn't exist on interface, but I need something like this    switch myStruct.(type) {       case MyStruct:           // ok           break       case *MyStruct:           // error here           break    }    switch myPointerToStruct.(type) {       case MyStruct:           // error here           break       case *MyStruct:           // ok           break    }}代码较长,但至少您不需要使用该reflect包。
随时随地看视频慕课网APP

相关分类

Go
我要回答