3 回答
TA贡献2003条经验 获得超2个赞
如果您知道接口的“真实”类型,则可以简单地使用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包。
- 3 回答
- 0 关注
- 411 浏览
添加回答
举报
