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

标签 go

如果我将接口(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")
    }
}

最佳答案

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() 就足够了。

关于go - 我如何判断我的 interface{} 是否是一个指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31285493/

相关文章:

sql - Golang pq sql 驱动程序 : get record ids after bulk import

go - reflect.Value.Set 使用无法寻址的值

Go: 读取 http.Request 中的方法

json - 从 relfect.Value 编码 JSON

docker - 如果有多个微服务,我应该如何集成测试它们?

api - 如何找出 Go 标准库函数的可能错误值?

go - “godef: There must be at least one package that contains the file”即使该文件确实具有包?

go - 在 golang 中使用 psexec 时缺少标准输出

git - 如何配置 gogs 以快速加载大型 git 存储库?

html - 从 [] 字符串中自动选择 select2